繁体   English   中英

无法将类型“ [String]”的值分配给类型“ String?”

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

我无法在indexPath的tableView委托方法cellForRow中调用数组。 它给出一个错误信息:

无法将字符串类型的值分配给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
    }
}

代码未构建。 我绑在方括号中,但它仍然给出相同的错误。

其原因是因为这是[String] String数组

将此行更改为

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

这条线

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

错误是自我解释。

无法将类型“ [String]”的值分配给类型“ String?”

这意味着您正在将字符串数组(即[String])分配给不允许的字符串类型。

设置cell.textLabel?.text = ...请确保您分配的是String type而不是[String] type

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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