Tusker/Tusker/Preferences/Preference.swift

61 lines
1.6 KiB
Swift
Raw Normal View History

2019-06-14 00:53:17 +00:00
// Preference.swift
// Tusker
//
// Created by Shadowfacts on 6/13/19.
// Copyright © 2019 Shadowfacts. All rights reserved.
//
import SwiftUI
@propertyWrapper
2019-08-07 20:59:11 +00:00
struct Preference<Value> {
2019-06-14 00:53:17 +00:00
let path: WritableKeyPath<Preferences, Value>
let binding: Binding<Value>
init(_ path: WritableKeyPath<Preferences, Value>) {
self.path = path
2019-08-06 03:08:00 +00:00
self.binding = Binding(get: {
2019-06-14 00:53:17 +00:00
return Preferences.shared[keyPath: path]
2019-08-06 03:08:00 +00:00
}, set: { (newValue) in
2019-06-14 00:53:17 +00:00
Preferences.shared[keyPath: path] = newValue
})
}
2019-07-18 22:44:35 +00:00
var wrappedValue: Value {
2019-06-14 00:53:17 +00:00
get {
return Preferences.shared[keyPath: path]
}
set {
Preferences.shared[keyPath: path] = newValue
}
}
}
@propertyWrapper
2019-08-07 20:59:11 +00:00
struct MappedPreference<Value, PrefValue> {
2019-06-14 00:53:17 +00:00
let path: WritableKeyPath<Preferences, PrefValue>
let fromPref: (PrefValue) -> Value
let toPref: (Value) -> PrefValue
let binding: Binding<Value>
init(_ path: WritableKeyPath<Preferences, PrefValue>, fromPref: @escaping (PrefValue) -> Value, toPref: @escaping (Value) -> PrefValue) {
self.path = path
self.fromPref = fromPref
self.toPref = toPref
2019-08-06 03:08:00 +00:00
self.binding = Binding(get: {
2019-06-14 00:53:17 +00:00
return fromPref(Preferences.shared[keyPath: path])
2019-08-06 03:08:00 +00:00
}, set: { (newValue) in
2019-06-14 00:53:17 +00:00
Preferences.shared[keyPath: path] = toPref(newValue)
})
}
2019-07-18 22:44:35 +00:00
var wrappedValue: Value {
2019-06-14 00:53:17 +00:00
get {
return fromPref(Preferences.shared[keyPath: path])
}
set {
Preferences.shared[keyPath: path] = toPref(newValue)
}
}
}