-1

假设以下字典:

var example: [String: (identifier: String, regex: NSRegularExpression)] = ["test": (identifier: "example", regex: try! NSRegularExpression(pattern: "test", options: []))]

我想按如下方式存储它:

let keyStore = NSUbiquitousKeyValueStore.default()
keyStore.set(example, forKey: "ex")

我的问题是当我尝试访问它时:

let test: [String: (identifier: String, regex: NSRegularExpression)] = keyStore.dictionary(forKey: "ex") as! [String: (identifier: String, regex: NSRegularExpression)]

我收到以下错误:

展开的可选值

为什么是这样?

4

1 回答 1

1

您正试图将您的字典交给需要 Objective-C NSDictionary 的 Objective-C;但是您不能将 Swift 元组作为值存储在 Objective-C NSDictionary 中。而且,NSUbiquitousKeyValueStore 的规则更加严格:不仅必须是 NSDictionary,而且只能使用属性列表类型,这是极其有限的。您需要执行一些操作,例如将 CGSize 包装在 NSValue 中并将其存档到 NSData 以便在此处使用它:

    let sz = CGSize(width:10, height:20)
    let val = NSValue(cgSize:sz)
    let dat = NSKeyedArchiver.archivedData(withRootObject: val)
    let example = ["test": dat]

    let keyStore = NSUbiquitousKeyValueStore.default()
    keyStore.set(example, forKey: "ex")

要取回该值,请反转该过程。

    if let dict = keyStore.dictionary(forKey: "ex") {
        if let ex = dict["test"] as? Data {
            if let v = NSKeyedUnarchiver.unarchiveObject(with: ex) as? NSValue {
                print(v.cgSizeValue) // (10.0, 20.0)
            }
        }
    }
于 2017-01-07T18:26:12.567 回答