Guest User

Untitled

a guest
Oct 23rd, 2017
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. protocol DictionaryRepresentable: class {
  2. associatedtype SelfType = Self
  3. func asDictionary() -> [String:Any]
  4. static func from(dictionary: [String:Any]) -> SelfType?
  5. static func from(dictionaries: [[String:Any]]) -> [SelfType]
  6. }
  7.  
  8. extension Array where Element:DictionaryRepresentable {
  9. func asDictionaries() -> [[String:Any]] {
  10. return self.map({ (representable) -> [String:Any] in
  11. return representable.asDictionary()
  12. })
  13. }
  14. }
  15.  
  16.  
  17. // Here's what I wanted to do, but can't.
  18.  
  19. extension Array where Element == [String:Any] {
  20. func asType<Q:DictionaryRepresentable>() -> [Q] {
  21. return self.flatMap({ (dictionary) -> Q? in
  22. return Q.from(dictionary: dictionary)
  23. //Xcode says: "Cannot convert value of type 'Q.SelfType?' to closure result type '_?'"
  24. })
  25. }
  26. }
  27.  
  28.  
  29. // So I resorted to adding that third protocol method,
  30. // and at least gave it a default implementation, as seen below:
  31.  
  32. extension DictionaryRepresentable {
  33. static func from(dictionaries: [[String:Any]]) -> [SelfType] {
  34. return dictionaries.flatMap { (dict) -> SelfType? in
  35. return self.from(dictionary: dict)
  36. }
  37. }
  38. }
Add Comment
Please, Sign In to add comment