美文网首页
Swift4.0 Dictionary 遍历keys问题

Swift4.0 Dictionary 遍历keys问题

作者: 少年Amore | 来源:发表于2017-10-27 10:28 被阅读0次

    swift4.0遍历key有点麻烦,请问有没有更好的方法?
    数据存储方式为:

    let sourceDic: [string: [string]] = [
      "Asia":["China", "Japan"],
      "Africa":["Egypt", "Morocco"]
    ]
    

    使用方式为,key为table.sectionName, value 为section.cell 显示内容。
    在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'
    

    意思是,不能对Dictionary<String, [String]>类型使用Int下标,然而在我的认知里,keys是数组而不是Dictionary。

    查Dictionary.keys API,发现果然返回是字典,懵逼脸。

     @available(swift 4.0)
        public var keys: Dictionary<Key, Value>.Keys { get }
    

    附带有用法说明:

        ///     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"
    

    然而我并不需要如此遍历,很不方便。
    进一步查询官方教程 Apple Inc. “The Swift Programming Language (Swift 4)”
    给出例子如下:

    “var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]”
    
    “let airportCodes = [String](airports.keys)
    // airportCodes is ["YYZ", "LHR"]
     
    let airportNames = [String](airports.values)”
    // airportNames is ["Toronto Pearson", "London Heathrow"]
    
    摘录来自: Apple Inc. “The Swift Programming Language (Swift 4)”
    
    

    所以,必须使用强转喽?于是代码变成如下模样,说好swift的优雅呢?

            let key = ([String](self.sourceDic.keys))[indexPath.section]
            let list = self.sourceDic[key]
            let text = list![indexPath.row]
    

    相关文章

      网友评论

          本文标题:Swift4.0 Dictionary 遍历keys问题

          本文链接:https://www.haomeiwen.com/subject/rwkmsxtx.html