Skip to main content
 首页 » 操作系统

arrays之Swift 字典查找导致编译时错误

2024年01月01日42xiaohuochai

我正在尝试 Swift,但遇到了一个让我有点困惑的问题。给定一个整数索引,我试图获取字典的相应键并返回与其关联的值。

以下面的结构为例:

Class CustomClass { 
    private var collection: [String: [SifterIssue]] = ["MyStringKey": [MyCustomCollectionClass]()] 
 
    /* ... */ 
} 

我试过这样解决问题:

var keys = Array(self.collection.keys) 
var key: String = keys[section] as String 
return self.collection[key].count // error is flagged here 

但发现这会导致编译器错误,该错误表明'String' 无法转换为'DictionaryIndex'。难倒了,我尝试了一个稍微冗长的解决方案,并惊讶地发现这个编译和工作没有问题。

var keys = Array(self.collection.keys) 
var key: String = keys[section] as String 
var collection: [MyCustomCollectionClass] = self.collection[key]! as [MyCustomCollectionClass] 
return issues.count 

谁能向我解释为什么第一个解决方案拒绝编译?

请您参考如下方法:

正如@Zaph 所说,忽略潜在的 fatal error 是一个坏主意,而 swift 在某种程度上是为了帮助解决这个问题。这是我能想出的最“敏捷”的代码:

func collectionCount(#section: Int) -> Int? { 
    switch section { 
    case 0..<collection.count: // Make sure section is within the bounds of collection's keys array 
        let key = collection.keys.array[section] // Grab the key from the collection's keys array 
        return collection[key]!.count // We can force unwrap collection[key] here because we know that key exists in collection 
    default: 
        return nil 
    } 
} 

它使用 swift 的 switch 语句的范围/模式匹配特性来确保 section 在 collection 的 范围内>keys 数组;这感觉比使用 if 更“敏捷”,主要是因为我找不到在 if 语句中使用 swift 的 Range 的方法。它还使用 collection.keys 惰性属性 array 作为快捷方式,而不是使用 Array(collection.keys)< 创建新的 Array/。因为我们已经确保 section 在 collection.keys 的范围内,所以我们可以强行打开 collection[key]! 当我们获取它的计数。

为了好玩,我还制作了一个通用函数,它将集合作为输入来概括事物:

func collectionCount<T,U>(#collection: [T:[U]], #section: Int) -> Int? { 
    switch section { 
    case 0..<collection.count: // Make sure section is within the bounds of collection's keys array 
        let key = collection.keys.array[section] // Grab the key from the collection's keys array 
        return collection[key]!.count // We can force unwrap collection[key] here because we know that key exists in collection 
    default: 
        return nil 
    } 
} 

[T:[U]] 基本上是说 collection 需要是一个 Dictionary 键 T其值为 U 的 Array。