Mapping a dictionary to an array of structs in Swift

对着背影说爱祢 提交于 2019-12-23 04:48:29

问题


My app needs to represent an array of presets, where a preset is represented by the following struct:

struct Preset: Codable {
    var name: String
    var value: Int
}

Using NSUserDefaultsController, NSTableView and CocoaBindings, I was able to create a Preferences window where I can add and remove presets, as well as edit them. They are persisted to the UserDefaults plist as follows:

<plist version="1.0">
<dict>
    <key>presets</key>
    <array>
        <dict>
            <key>name</key>
            <string>A preset</string>
            <key>value</key>
            <integer>1</integer>
        </dict>
        <dict>
            <key>name</key>
            <string>Another preset</string>
            <key>value</key>
            <integer>2</integer>
        </dict>
    </array>
</dict>
</plist>

I'm looking to access this data in my code using a natural notation. Basically, I'd like to have a Settings singleton with a computed property like this:

class Settings: NSObject {
    static let sharedInstance = Settings()
    private let presetsKey = "presets"

    override private init() {
        UserDefaults.standard.register(defaults: [
            presetsKey: [ ["name": "Default preset", "value": 0] ],
        ])

        super.init()
    }

    var presets: [Preset] {
        get {
            // Missing code goes here
        }
    }
}

The code in the getter should perform the mapping from the preset UserDefaults array to [Preset], in place of the // Missing code goes here comment. Here's an example of the notation I'd like to use:

let firstPresetName = Settings.sharedValue.preset[0].name
let firstPresetValue = Settings.sharedValue.preset[0].value
print("The first preset's name is \(firstPresetName\) and its value is \(firstPresetValue\)")

I wrote this, and it works:

let presets = UserDefaults.standard.array(forKey: presetsKey) as! [[String: Any]]
var result = [Preset]()
for preset in presets {
    result.append(ControlParameters(name:preset["name"] as! String, value:preset["value"] as! Int))
}
return result

Yet I'm not happy with this solution. Is there a more compact and generic solution (which works for any struct in a similar context, without having to hardcode the struct property names such as name and value)?


回答1:


You can use a PropertyListDecoder to directly decode your property list file:

struct Preset: Codable {
    var name: String
    var value: Int
}

struct Presets : Codable {
    let presets: [Preset]
}

let decoder = PropertyListDecoder()
let presets = try? decoder.decode(Presets.self, from: yourPropertyListData)



回答2:


This gist allowed me solve the problem, with a few modifications:

extension UserDefaults {
    func encode<T: Encodable>(_ value: T?, forKey key: String) throws {
        switch T.self {
        case is Float.Type, is Double.Type, is String.Type, is Int.Type, is Bool.Type:
            set(value!, forKey: key)
        default:
            let data = try value.map(PropertyListEncoder().encode)
            let any = data.map { try! PropertyListSerialization.propertyList(from: $0, options: [], format: nil) }

            set(any, forKey: key)
        }
    }

    func decode<T: Decodable>(_ type: T.Type, forKey key: String) throws -> T? {
        switch T.self {
        case is Float.Type, is Double.Type, is String.Type, is Int.Type, is Bool.Type:
            return (value(forKey: key) as! T)
        default:
            let any = object(forKey: key)
            let data = any.map { try! PropertyListSerialization.data(fromPropertyList: $0, format: .binary, options: 0) }

            return try data.map { try PropertyListDecoder().decode(type, from: $0) }
        }
    }
}

Using this, I can define the following generic functions:

private func getter<T: Codable>(key: String) -> T {
    let result = try! UserDefaults.standard.decode(T.self, forKey: key)
    return result!
}

private func setter<T: Codable>(_ newValue: T, forKey key: String) {
    try! UserDefaults.standard.encode(newValue, forKey: key)
}

Now I can implement computed getters and setters for all of my properties as such:

var presets: [Preset] {
    get {
       return getter(presetsKey)
    }

    set {
       setter(newValue, presetsKey)
    }
}

It also works for non-array types.



来源:https://stackoverflow.com/questions/54381536/mapping-a-dictionary-to-an-array-of-structs-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!