swift4.0遍歷key有點(diǎn)麻煩,請(qǐng)問(wèn)有沒(méi)有更好的方法辰如?
數(shù)據(jù)存儲(chǔ)方式為:
let sourceDic: [string: [string]] = [
"Asia":["China", "Japan"],
"Africa":["Egypt", "Morocco"]
]
使用方式為,key為table.sectionName, value 為section.cell 顯示內(nèi)容。
在cellForRow方法中代碼如下
let key = self.sourceDic.keys[indexPath.section]
let list = self.sourceDic[key]
let text = list![indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
cell?.textLabel?.text = text
得到編譯Error:
Cannot subscript a value of type 'Dictionary<String, [String]>.Keys' with an index of type 'Int'
意思是邮破,不能對(duì)Dictionary<String, [String]>類(lèi)型使用Int下標(biāo)酱酬,然而在我的認(rèn)知里壶谒,keys是數(shù)組而不是Dictionary。
查Dictionary.keys API膳沽,發(fā)現(xiàn)果然返回是字典汗菜,懵逼臉让禀。
@available(swift 4.0)
public var keys: Dictionary<Key, Value>.Keys { get }
附帶有用法說(shuō)明:
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// for k in countryCodes.keys {
/// print(k)
/// }
/// // Prints "BR"
/// // Prints "JP"
/// // Prints "GH"
然而我并不需要如此遍歷,很不方便陨界。
進(jìn)一步查詢(xún)官方教程 Apple Inc. “The Swift Programming Language (Swift 4)”
給出例子如下:
“var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]”
“l(fā)et airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]
let airportNames = [String](airports.values)”
// airportNames is ["Toronto Pearson", "London Heathrow"]
摘錄來(lái)自: Apple Inc. “The Swift Programming Language (Swift 4)”
所以巡揍,必須使用強(qiáng)轉(zhuǎn)嘍?于是代碼變成如下模樣普碎,說(shuō)好swift的優(yōu)雅呢吼肥?
let key = ([String](self.sourceDic.keys))[indexPath.section]
let list = self.sourceDic[key]
let text = list![indexPath.row]