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

标签 arrays dictionary collections swift

我正在尝试 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 语句的范围/模式匹配特性来确保 sectioncollection 范围内>keys 数组;这感觉比使用 if 更“敏捷”,主要是因为我找不到在 if 语句中使用 swift 的 Range 的方法。它还使用 collection.keys 惰性属性 array 作为快捷方式,而不是使用 Array(collection.keys)< 创建新的 Array/。因为我们已经确保 sectioncollection.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 需要是一个 DictionaryT其值为 UArray

关于arrays - Swift 字典查找导致编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25350560/

相关文章:

python - 我怎样才能得到一个字典来生成两个具有相同键的字典

java - 在没有 ConcurrentModificationException 的情况下使用 ArrayList 的方法?

mysql - Magento - addOrderedQty 多个日期

c++ - 将 8 个字节转换为 double 值

ios - 如何从我的数组中删除 "..."?

javascript - 如何获得按对象键过滤的唯一对象数组?

arrays - gdb:打印二维fortran数组

python:在字典中创建一个列表

ios - 如何使用 SearchBar TableView 在字典中搜索对象?

c# - 是否有类似 List<T> 的动态数组允许访问 .NET 中的内部数组数据?