简体   繁体   中英

Cannot assign value of type '[String]' to type 'String?'

I can't call array in the tableView delegate method cellForRow at indexPath. it gives an error message:

Cannot assign value of type string to typeString?

import UIKit

struct cellData {
    var open = Bool()
    var currentRides = [String]()
    var RequestedRides = [String]()
    var sectionData = [String]()
}

class RideResultViewController: ContentViewController,  UITableViewDelegate, UITableViewDataSource {
    let currentRidesArray = ["1", "2", "3"]
    let RequestedRidesArray = ["A", "B", "C"]

    var tableViewData = [cellData]()

    @IBAction func segmentedValueChanged(_ sender: Any) {
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //Expandable cell initailization
        tableViewData = [cellData(open: false, currentRides: currentRidesArray, RequestedRides: RequestedRidesArray, sectionData: ["cell1", "cell2", "cell3"])]
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()}
        if segmentedControl.selectedSegmentIndex == 0 {
            cell.textLabel?.text =   tableViewData[indexPath.section].currentRides
        } else if segmentedControl.selectedSegmentIndex == 1 {
            cell.textLabel?.text =    RequestedRidesArray[indexPath.row]
        }

        return cell
    } else {
        guard let cell =     tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()}
        if segmentedControl.selectedSegmentIndex == 0 {
            cell.textLabel?.text = tableViewData[indexPath.section].sectionData[indexPath.row]
        } else if segmentedControl.selectedSegmentIndex == 1 {
            cell.textLabel?.text =    tableViewData[indexPath.section].sectionData[indexPath.row]
        }

        return cell
    }
}

The code not building. I tied to put it in a square bracket but it still gave same error.

Its because this is [String] an array of String

Change this line to

cell.textLabel?.text =   tableViewData[indexPath.section].currentRides

This line

cell.textLabel?.text =   tableViewData[indexPath.section].currentRides[indexPath.row]

The error is self explainary..

Cannot assign value of type '[String]' to type 'String?'

It means you are assigning an array of string ie [String] to string type which is not allowed.

When you are setting cell.textLabel?.text = ... please make sure that you are assigning String type not [String] type .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM