【问题标题】:Access a value in a dictionary using an int variable in Swift在 Swift 中使用 int 变量访问字典中的值
【发布时间】:2019-06-08 18:30:47
【问题描述】:

我正在开发一个 iOS 应用,我想使用 Array() 访问字典中的特定值。

我的字典包含一个数组,其中包含结构。

let array = [(key: "S", value: [Thunderbolt.repoStruct(repoName: "Semiak Repo", repoURL: "https://repo.semiak.dev", icon: Optional("iconRound"))]), (key: "T", value: [Thunderbolt.repoStruct(repoName: "Thunderbolt iOS Utilities", repoURL: "https://repo.thunderbolt.semiak.dev", icon: Optional("iconRound"))])]

我正在用数组创建一个UITableView:部分名称是key 值,单元格标题是repoStruct.repoName 值,以下值相同。

要访问 repoName,我会使用 Array(array)[0].1[0].repoName

问题是我不知道我想访问的确切位置,而是使用 indexPath 来知道我需要哪个值:

Array(array)[indexPath.section].indexPath.row[0].repoName

这应该返回单元格的 repoName,但是却给了我以下错误:Value of tuple type '(key: String, value: [repoStruct])' has no member 'indexPath'

我也尝试过使用:

let row = indexPath.row
Array(array)[indexPath.section].row[0].repoName

但它给了我同样的错误:Value of tuple type '(key: String, value: [repoStruct])' has no member 'row'

我不知道为什么 Array(array)[0].1 有效并返回值,但 Array(array)[indexPath.section].row 没有。它也是这样做的:使用位置访问一个值,它是一个 int,例如 indexPath。

我怎样才能做到这一点?

提前致谢。

【问题讨论】:

    标签: arrays swift dictionary tuples nsdictionary


    【解决方案1】:

    强烈建议您不要在数据源数组中使用元组。用额外的结构替换元组

    struct Section {
        let name : String
        let items : [Thunderbolt.repoStruct]
    }
    
    let array = [Section(name: "S", items: [Thunderbolt.repoStruct(repoName: "Semiak Repo", repoURL: "https://repo.semiak.dev", icon: Optional("iconRound"))], 
                 Section(name: "T", items: [Thunderbolt.repoStruct(repoName: "Thunderbolt iOS Utilities", repoURL: "https://repo.thunderbolt.semiak.dev", icon: Optional("iconRound"))]]
    

    并在索引路径获取项目

    let section = array[indexPath.section]
    let item = section.items[indexPath.row]
    let name = item.repoName
    

    【讨论】:

      【解决方案2】:

      首先,您的array 已经是一个数组,因此无需说Array(array) - 只需array 就足够了,尽管应该避免使用这样的通用名称。

      我不知道为什么array[0].1[0] 有效

      让我们把它分开 - 你通过[0] 访问array 中的第一个元素,在其中访问元组.1 的第二个元素,最后是那个valuearray 的第一个元素。您可以使用array[0].value[0] 获得相同的效果并使代码更具可读性。

      array[indexPath.section].row 没有

      这是因为您的数组不包含任何名为 row 的内容。

      请改用array[indexPath.section].value[indexPath.row].repoName

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多