sindresorhus / Defaults

💾 Swifty and modern UserDefaults
https://swiftpackageindex.com/sindresorhus/Defaults/documentation/defaults
MIT License
1.97k stars 117 forks source link

How are custom nested types use? #116

Closed GanZhiXiong closed 1 year ago

GanZhiXiong commented 1 year ago

I am new to swift and I know how to use Custom types, see https://github.com/sindresorhus/Defaults#custom-types.

But how to use nested custom types? How to implement Address like in the code below?

public struct Address {
    var city: String
    var cityCode: Int
}

public struct User: Hashable, Equatable {
    var username: String
    var password: String
    var address: Address
}

extension User: Defaults.Serializable {
    public static let bridge = DefaultsUserBridge()
}

public final class DefaultsUserBridge: Defaults.Bridge {
    public typealias Value = User
    public typealias Serializable = [String: String]

    public func serialize(_ value: Value?) -> Serializable? {
        guard let value = value else {
            return nil
        }

        return ["username": value.username,
                "password": value.password,
                "address": ...
        ]
    }

    public func deserialize(_ object: Serializable?) -> Value? {
        guard
            let object = object,
            let username = object["username"],
            let password = object["password"]
        else {
            return nil
        }

        return User(username: username, password: password, address: ...)
    }
}
hank121314 commented 1 year ago

Duplicate of #101

hank121314 commented 1 year ago

Close as #101 is completed.