How can I get all writable keypaths from a Swift struct programatically? - swift

I'm trying to convert a `struct1 to Realm objects right now.
Realm object has same keypath with original struct.
so If I can get all writable keypaths from original struct, it is possible to convert with general method.
public protocol KeyPathListable {
var allKeyPaths:[WritableKeyPath<Self, Any>] { get }
}
extension KeyPathListable {
private subscript(checkedMirrorDescendant key: String) -> Any {
return Mirror(reflecting: self).descendant(key)!
}
var allKeyPaths:[WritableKeyPath<Self, Any>] {
var membersTokeyPaths = [WritableKeyPath<Self,Any>]()
let mirror = Mirror(reflecting: self)
for case (let key?, _) in mirror.children {
if let keyPath = \Self.[checkedMirrorDescendant: key] as? WritableKeyPath<Self, Any> {
membersTokeyPaths.append(keyPath)
}
}
return membersTokeyPaths
}
}
Just found the code snippet above but it returns KeyPath(not WritableKeyPath). I tried to typecast in this case, but it returns nil. Maybe mirror function has problem. Is there any solution for that?

Related

Combine these into a single var

Apologies for the stupid question, I'm still really new to the Swift language.
Following up on this answer by #matt, I want to combine these two statements into a single var
UserDefaults.standard.set(try? PropertyListEncoder().encode(songs), forKey:"songs")
if let data = UserDefaults.standard.value(forKey:"songs") as? Data {
let songs2 = try? PropertyListDecoder().decode(Array<Song>.self, from: data)
}
I've thought maybe using a var with didSet {} like something along the lines of
var test: Array = UserDefaults.standard. { // ??
didSet {
UserDefaults.standard.set(try? PropertyListEncoder().encode(test), forKey: "songs")
}
}
But I can't think of where to go from here.
Thanks for the help in advance :))
The property should not be a stored property. It should be a computed property, with get and set accessors:
var songsFromUserDefaults: [Song]? {
get {
if let data = UserDefaults.standard.value(forKey:"songs") as? Data {
return try? PropertyListDecoder().decode(Array<Song>.self, from: data)
} else {
return nil
}
}
set {
if let val = newValue {
UserDefaults.standard.set(try? PropertyListEncoder().encode(val), forKey:"songs")
}
}
}
Notice that since the decoding can fail, the getter returns an optional. This forces the setter to accept an optional newValue, and I have decided to only update UserDefaults when the value is not nil. Another design is to use try! when decoding, or return an empty array when the decoding fails. This way the type of the property can be non-optional, and the nil-check in the setter can be removed.
While you can use computed properties like Sweeper suggested (+1), I might consider putting this logic in a property wrapper.
In SwiftUI you can use AppStorage. Or you can roll your own. Here is a simplified example:
#propertyWrapper public struct Saved<Value: Codable> {
private let key: String
public var wrappedValue: Value? {
get {
guard let data = UserDefaults.standard.data(forKey: key) else { return nil }
return (try? JSONDecoder().decode(Value.self, from: data))
}
set {
guard
let value = newValue,
let data = try? JSONEncoder().encode(value)
else {
UserDefaults.standard.removeObject(forKey: key)
return
}
UserDefaults.standard.set(data, forKey: key)
}
}
init(key: String) {
self.key = key
}
}
And then you can do things like:
#Saved(key: "username") var username: String?
Or
#Saved(key: "songs") var songs: [Song]?

How can I implement a generic struct that manages key-value pairs for UserDefaults in Swift?

How would one implement a struct that manages UserDefaults mappings in Swift?
Right now I have some computed properties a, b, c, d of different types and corresponding keys that look like this:
enum UserDefaultsKeys {
a_key
b_key
...
}
var a: String {
get { UserDefaults.standard.string(forKey: UserDefaultsKeys.a_key.rawValue) }
set { UserDefaults.standard.set(newValue, forKey: UserDefaultsKeys.a_key.rawValue) }
}
var b: Int {
get { UserDefaults.standard.integer(forKey: UserDefaultsKeys.b_key.rawValue) }
set { UserDefaults.standard.set(newValue, forKey: UserDefaultsKeys.b_key.rawValue) }
}
...
What I would like to achieve instead is to implement a struct that has a key of type String and a generic type value.
The value get function should - depending on its type - chose wether to use UserDefaults.standard.string or UserDefaults.standard.integer so that I can just create a DefaultsVar with some key and everything else is managed automatically for me.
What I have so far is this:
struct DefaultsVar<T> {
let key: String
var value: T {
get {
switch self {
case is String: return UserDefaults.standard.string(forKey: key) as! T
case is Int: return UserDefaults.standard.integer(forKey: key) as! T
default: return UserDefaults.standard.float(forKey: key) as! T
}
}
set { UserDefaults.standard.set(newValue, forKey: key) }
}
}
I get the following error: "Cast from DefaultsVar to unrelated Type 'String' always fails.
I am completely new to swift (and relatively new to programming) and don't really understand how to implement this the right way - or if this is even an approach that would be considered a good practice. Could someone please shine some light on this?
Thank you in advance!
You can use a custom
Property wrapper:
#propertyWrapper
struct UserDefaultStorage<T: Codable> {
private let key: String
private let defaultValue: T
private let userDefaults: UserDefaults
init(key: String, default: T, store: UserDefaults = .standard) {
self.key = key
self.defaultValue = `default`
self.userDefaults = store
}
var wrappedValue: T {
get {
guard let data = userDefaults.data(forKey: key) else {
return defaultValue
}
let value = try? JSONDecoder().decode(T.self, from: data)
return value ?? defaultValue
}
set {
let data = try? JSONEncoder().encode(newValue)
userDefaults.set(data, forKey: key)
}
}
}
This wrapper can store/restore any kind of codable into/from the user defaults.
Usage
#UserDefaultStorage(key: "myCustomKey", default: 0)
var myValue: Int
iOS 14
SwiftUI has a similar wrapper (only for iOS 14) called #AppStorage and it can be used as a state. The advantage of using this is that it can be used directly as a State. But it requires SwiftUI and it only works from the iOS 14.

Defining swift extensions with generic functions for realm and object mapper

I am working with Realm and ObjectMapper and would like to create some extensions to make my life easier when backing up some data to JSON. I have the following extensions defined:
extension Mappable where Self:Object {
func getCompleteJSONDictionary() throws -> [String: Any]? {
var returnValue: [String: Any]?
if self.isManaged, let realm = self.realm, !realm.isInWriteTransaction {
try realm.write {
var data = self.toJSON()
data["id"] = self.getPrimaryKeyValue()
returnValue = data
}
} else {
var data = self.toJSON()
data["id"] = self.getPrimaryKeyValue()
returnValue = data
}
return returnValue
}
}
extension Results where Element:Object, Element:Mappable {
func getAllCompleteJSONDictionaries() throws -> Array<[String:Any]>? {
var array: Array<[String:Any]> = Array()
for element in self {
if let dictionary = try? element.getCompleteJSONDictionary(), let data = dictionary {
array.append(data)
}
}
if array.count > 0 {
return array
} else {
return nil
}
}
}
extension Realm {
func getJSONBackupData<T>(forTypes types: [T.Type]) throws -> [String: Any] where T:Object, T:Mappable {
var data: [String: Any] = [:]
try self.write {
for type in types {
let entities = self.objects(type)
if let entityJsonData = try entities.getAllCompleteJSONDictionaries() {
data[String(describing: type)] = entityJsonData
}
}
}
return data
}
}
The first two extensions work fine, but as soon as I try to use the last, the country class conforms to both Object and Mappable:
var finalData = realm.getJSONBackupData(forTypes:[Country.self])
I get an error that T cannot be inferred. I still get myself hopelessly muddled when it comes to generics in Swift so am guessing i am just not understanding the problem correctly. Is there an easy fix here or have I asked too much of the compiler?
The problem is that the Realm Objects does not conform to Mappable Protocol. So the Country Object is not Mappable and thus the complier is saying that Type Country.self cannot be inferred as Object and Mappable.

Swift Get all the properties in generic class

I'm trying to get all the members of a generic class T, I can get the properties based on a specific class.
But, how I can do it using Mirror ?
let mirrored_object = Mirror(reflecting: user)
for (index, attr) in mirrored_object.children.enumerated() {
if let propertyName = attr.label as String! {
print("Attr \(index): \(propertyName) = \(attr.value)")
}
}
I added this as extension
extension NSObject {
public func GetAsJson() -> [[String:Any?]] {
var result:[[String: Any?]] = [[String: Any?]]()
for item in self {
var dict: [String: Any?] = [:]
for property in Mirror(reflecting: self).children {
dict[property.label!] = property.value
}
result.append(dict)
}
return result
}
}

KVC Swift 2.1 Reflection

I'm attempting to implement a KVC equivalent is Swift (inspired by David Owens) using reflection.
valueForKey is fairly trivial, using reflection to get all the children names and retrieve the appropriate value. setValueForKey has proved to be quite tricky however, as Swift reflection appears to be read-only (since readwrite would break reflections dogma)
protocol KVC {
var codeables: [String: Any.Type] { get }
mutating func setValue<T>(value: T, forKey key: String)
func getValue<T>(key: String) -> T?
}
extension KVC {
var codeables: [String: Any.Type] {
var dictionary: [String: Any.Type] = [:]
let mirror = Mirror(reflecting: self)
for child in mirror.children {
if let label = child.label {
dictionary[label] = Mirror(reflecting: child.value).subjectType
}
}
return dictionary
}
mutating func setValue<T>(value: T, forKey key: String) {
if let valueType = self.codeables[key] where valueType == value.dynamicType {
}
}
func getValue<T>(key: String) -> T? {
let mirror = Mirror(reflecting: self)
for child in mirror.children {
if let label = child.label, value = child.value as? T where label == key {
return value
}
}
return nil
}
}
Is there anyway in Swift at all to set a dynamic keypath value without using the Objective-C runtime or enforcing that the conformer is a subclass of NSObject? It seems like the answer is no but there are some clever workarounds such as ObjectMapper, although I'm not a fan of the responsibility its on the conformer.