Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct JSON {
- let json: [String: Any]
- func value<Value>(_ key: String) throws -> Value {
- guard let value = json[key] as? Value else { throw NSError() }
- return value
- }
- }
- protocol JSONDeserializable {
- init(json: JSON) throws
- }
- protocol UserModel: JSONDeserializable {
- var username: String { get set } // Unwanted requirement (UR) #1: property needs "set" so that it can be initialized within protocol
- init() // UR2: needs empty init, because of default implementation of `init(json: JSON)` in `extension UserModel`
- }
- extension UserModel {
- init(json: JSON) throws {
- self.init() // UR3: Needs to call this otherwise compilation error: `'self' used before chaining to another self.init requirement`
- username = try json.value("username")
- }
- }
- struct UserStruct: UserModel {
- // UR4: property cannot be `let`, beause of `set` in protocol.
- var username: String = "" // UR5: Property have to have default value because of it being a empty init
- init() {}
- }
- final class UserClass: NSObject, UserModel {
- // UR6: analogue with UR4
- var username: String = "" // UR7: analogue with UR5
- }
- let json: JSON = JSON(json: ["username": "Sajjon"])
- let u1 = try UserStruct(json: json)
- let u2 = try UserClass(json: json)
- print(u1.username) // prints "Sajjon"
- print(u2.username) // prints "Sajjon"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement