How to Get An Array of Keys from NSUbiquitousKeyValueStore.default()?

526 views Asked by At

I have a key-value store, and I want a list of the keys so that I can assign an identifier to each struct. I can do this in a Playground, however the same code does not work in Xcode, and produces the following error:

'Attribute' is not convertible to '<< error type' >>

On this line of code:

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

The complete code for the Playground is as follows:

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!)

In Xcode, I have the Attributes Struct:

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
    }
}

The following Protocol:

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

And these two extensions:

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

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

Again, the version in the Playground works perfectly, so what what would be the problem with the other?

EDIT 1: Here is all of the code:

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

There are 0 answers