【问题标题】:swift print element in array at the indexPath.row在 indexPath.row 的数组中快速打印元素
【发布时间】:2019-08-27 11:20:25
【问题描述】:

想在数组中的元素处打印字符串

var twoDimensionalArray = [
    ExpandableNames(isExpanded: false, names: ["Antiques",
        "Art",
        "Collectables",
        "Other Antiques , Art & Collectables"]),


    ExpandableNames(isExpanded: false, names: ["Baby Carriers",
        "Baby Clothing",
        "Baths",
        "Safety"]),
]


override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


    let mm = twoDimensionalArray[indexPath.row]

  if indexPath == [1,1]{
 print("this is mm:",mm)
 }

        }

//打印语句打印

mm is: ExpandableNames(isExpanded: true, names: ["Baby Clothing","Baths","Safety"])

我只想让它打印“婴儿背带”

【问题讨论】:

    标签: swift xcode didselectrowatindexpath


    【解决方案1】:

    假设ExpandableNames 是这样定义的

    struct ExpandableNames {
        var isExpanded: Bool
        var names: [String]
    } 
    

    您可以像这样在indexPath.row 检索第一项

    if let firstName = twoDimensionalArray[indexPath.row].names.first {
        //do something with firstName 
    }
    

    或者如果你想访问特定索引处的元素

    var index = 0
    let firstName = twoDimensionalArray[indexPath.row].names[index]
    

    【讨论】:

    • 对不起 Joakim Danielson 我刚刚意识到这只会打印索引 0 ,我将如何设置它以便索引成为我点击的每个索引?所以如果我点击第 1 行第 1 行,它会打印出每一个 twoDimensionalArray.names 在该行的内容?
    • 我猜我只是更改了每一行的代码行并将其更改为 index = 1 ,对于第 1 行, index = 2 ,对于第 2 行。除非有更好的方法?
    • 我也认为应该让 firstName = twoDimensionalArray[indexPath.section].names[index] - 将其从 inexPath.row 更改为 indexPath.section
    • 我将 index 声明为 var,因此可以对其进行更改,因此第二个选项可能是最好的。问题中没有提到部分,所以我看不出这有什么关系。
    • 是的,对不起,我正在寻找但没有正确解释的东西
    猜你喜欢
    • 2021-05-12
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多