如何从NSUbiquitousKeyValueStore.default()获取一系列键?

时间:2017-01-02 16:51:10

标签: swift cocoa protocols nsubiquitouskeyvaluestore

我有一个键值存储,我想要一个键列表,以便我可以为每个结构分配一个标识符。我可以在Playground中执行此操作,但是相同的代码在Xcode中不起作用,并产生以下错误:

  
    

'属性'不可转换为'<<错误类型' >>

  

在这行代码中:

for i in keyStore.dictionaryRepresentation.keys { keys.append(i) }

Playground的完整代码如下:

let keyStore = NSUbiquitousKeyValueStore.default()
keyStore.set("Test", forKey: "test")
var keys : [String] = []
for i in keyStore.dictionaryRepresentation.keys { keys.append(i) }
keyStore.string(forKey: keys.first!)

在Xcode中,我有属性结构:

struct Attribute: KVSAccessor {
    var identifier: String {return ""}
    var regex: NSRegularExpression

    init(kvsIndex: Int) {
        var keys: [String] = []
        for i in keyStore.dictionaryRepresentation.keys { keys.append(i) }
        guard let key = keys[kvsIndex] else { return }
        identifier = key
    }
}

以下议定书:

protocol KVSAccessor {
    var keyStore: NSUbiquitousKeyValueStore {get}
    func sync()
    var identifier: String {get set}
}

这两个扩展:

extension KVSAccessor where Self: Any { func sync() { NSUbiquitousKeyValueStore.default().synchronize() } }

extension KVSAccessor where Self: Attribute { var keyStore: NSUbiquitousKeyValueStore { return NSUbiquitousKeyValueStore.default() } }

同样,Playground中的版本运行完美,那么另一个版本会出现什么问题呢?

编辑1:这是所有代码:

import Foundation
import Cocoa

struct Attribute: KVSAccessor {
    var identifier: String {return ""}
    var regex: NSRegularExpression

    init(kvsIndex: Int) {
        var keys: [String] = []
        for i in keyStore.dictionaryRepresentation.keys { keys.append(i) }
        guard let key = keys[kvsIndex] else { return }
        identifier = key
    }
}

protocol KVSAccessor {
    var keyStore: NSUbiquitousKeyValueStore {get}
    func sync()
    var identifier: String {get set}
}

extension KVSAccessor where Self: Any { func sync() { NSUbiquitousKeyValueStore.default().synchronize() } }

extension KVSAccessor where Self: Attribute { var keyStore: NSUbiquitousKeyValueStore { return NSUbiquitousKeyValueStore.default() } }

0 个答案:

没有答案