如何使用 prepareForSegue 从二维数组传递值

How to pass value from 2d array with prepareForSegue

我在 tableView 中有一个这样的数组:

var array: [[String]] = [["Apples", "Bananas", "Oranges"], ["Round", "Curved", "Round"]]

我想在按下单元格时传递单元格的名称。使用标准数组我会这样做:

 let InfoSegueIdentifier = "ToInfoSegue"

    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.identifier == InfoSegueIdentifier
        {
            let destination = segue.destination as! InfoViewController
            let arrayIndex = tableView.indexPathForSelectedRow?.row
            destination.name = nameArray[arrayIndex!]
          }
    }    

并在接下来的ViewController (InfoViewController)

var name = String()


    override func viewDidLoad() {
        super.viewDidLoad()
nameLabel.text = name
    }    

错误:"Cannot assign value of type '[String]' to type 'String'"

更改这部分代码

if segue.identifier == InfoSegueIdentifier
{
     let destination = segue.destination as! InfoViewController
     let arrayIndex = tableView.indexPathForSelectedRow?.row
     destination.name = nameArray[arrayIndex!]
}

if segue.identifier == InfoSegueIdentifier
{
   let destination = segue.destination as! InfoViewController
   let arrayIndexRow = tableView.indexPathForSelectedRow?.row
   let arrayIndexSection = tableView.indexPathForSelectedRow?.section
   destination.name = nameArray[arrayIndexSection!][arrayIndexRow!]
 }

尝试并分享结果。

崩溃原因:在您的第一个 viewController 中,您有 [[String]] 这是您的数据源部分。现在,当您尝试从该数组中获取对象时,它将 returns 您 [String] 并且在您的目标 viewController 中,您拥有 字符串。并且在将 [String] 分配给 String 时会导致类型不匹配的崩溃。因此,上面的代码所做的是,它将首先从 arrayIndexSection 中获取 [String],然后是 String 来自 arrayIndexRow 并因此将 String 对象传递到目标。

希望一切顺利。

您收到此错误是因为您将一个数组传递给第二个视图控制器并且有一个字符串类型的变量。所以,像这样替换这个方法。

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.identifier == InfoSegueIdentifier
        {
            let destination = segue.destination as! InfoViewController
            if let indexPath = tableView.indexPathForSelectedRow{
                 destination.name = nameArray[indexPath.section][indexPath.row]
            }

        }
    }