Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. struct JSON {
  2. let json: [String: Any]
  3. func value<Value>(_ key: String) throws -> Value {
  4. guard let value = json[key] as? Value else { throw NSError() }
  5. return value
  6. }
  7. }
  8.  
  9. protocol JSONDeserializable {
  10. init(json: JSON) throws
  11. }
  12.  
  13. protocol UserModel: JSONDeserializable {
  14. var username: String { get set } // Unwanted requirement (UR) #1: property needs "set" so that it can be initialized within protocol
  15. init() // UR2: needs empty init, because of default implementation of `init(json: JSON)` in `extension UserModel`
  16. }
  17.  
  18. extension UserModel {
  19. init(json: JSON) throws {
  20. self.init() // UR3: Needs to call this otherwise compilation error: `'self' used before chaining to another self.init requirement`
  21. username = try json.value("username")
  22. }
  23. }
  24.  
  25. struct UserStruct: UserModel {
  26. // UR4: property cannot be `let`, beause of `set` in protocol.
  27. var username: String = "" // UR5: Property have to have default value because of it being a empty init
  28. init() {}
  29. }
  30.  
  31. final class UserClass: NSObject, UserModel {
  32. // UR6: analogue with UR4
  33. var username: String = "" // UR7: analogue with UR5
  34. }
  35.  
  36. let json: JSON = JSON(json: ["username": "Sajjon"])
  37. let u1 = try UserStruct(json: json)
  38. let u2 = try UserClass(json: json)
  39. print(u1.username) // prints "Sajjon"
  40. print(u2.username) // prints "Sajjon"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement