Swift中的Key和String如何相互转换?

How to convert between Key and String in Swift?

我正在对字典进行扩展,这只是一种遍历深层 json 结构以查找可能存在的给定字典的便捷方法。在字典的一般扩展中,我无法下标,因为我给出的是字符串而不是键

extension Dictionary {

    func openingHoursDictionary() -> Dictionary<String,AnyObject>? {   
        if let openingHours = self["openingHours"] as? Array<AnyObject> {
         // traverses further and finds opening hours dictionary 

        }
        return nil
    }
} 

Error: String is not convertible to DictionaryIndex<Key, Value> 
on self["openingHours"]

我如何从 String "openingHours" 中生成 Key 或检查字典中的字符串?

只需使用 "openingHours" as Key

String 转换为 Key
if let pickupPoints = self["openingHours" as Key] as? Array<AnyObject> {

}

缺点是,如果我有 Dictionary<Int,AnyObject> 并使用那里的方法,这样做会导致崩溃。

0x10e8c037d:  leaq   0x362aa(%rip), %rax       ; "Swift dynamic cast failure"

您可以在运行时检查字符串是否是字典的有效键:

extension Dictionary {

    func openingHoursDictionary() -> [String : AnyObject]? { 
        if let key = "openingHours" as? Key {
            if let openingHours = self[key] as? Array<AnyObject> {
                // traverses further and finds opening hours dictionary 
            }
        }
        return nil
    }
} 

但是如果需要其他词典,这将 "silently" return nil[Int, AnyObject].

如果您希望编译器检查下标是否安全 带有字符串的字典,那么您必须使用(通用)函数:

func openingHoursDictionary<T>(dict : [String : T]) -> [String : AnyObject]? {
    if let openingHours = dict["openingHours"] as? Array<AnyObject> {
        // traverses further and finds opening hours dictionary 
    }
    return nil
}

(目前)无法写入 Dictionary(或 Array) 仅适用于受限类型的扩展方法 通用参数。