在Swift中使用int变量访问字典中的值

时间:2019-06-08 18:30:47

标签: arrays swift dictionary tuples nsdictionary

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

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

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的值,并与以下值相同。 / p>

要访问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无效。这样做是一样的:使用作为整数的位置(例如indexPath)访问值。

我该怎么做?

谢谢。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

首先,您的array已经是一个数组,因此不必说Array(array)-简单地array就可以了,尽管应该避免使用这样的通用名称。

  

我不知道array[0].1[0]为何起作用

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

  

但是array[indexPath.section].row不是

那是因为您的数组不包含任何称为row的东西。

改为使用array[indexPath.section].value[indexPath.row].repoName

答案 2 :(得分:1)

请尝试使用此代码。

let dictData = arr[indexpath.section] //Element of section
let value = dictData["value"] //Value added in value in The element
let name = value[indexpath.row].reponame //Gives you name