Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- protocol DictionaryRepresentable: class {
- associatedtype SelfType = Self
- func asDictionary() -> [String:Any]
- static func from(dictionary: [String:Any]) -> SelfType?
- static func from(dictionaries: [[String:Any]]) -> [SelfType]
- }
- extension Array where Element:DictionaryRepresentable {
- func asDictionaries() -> [[String:Any]] {
- return self.map({ (representable) -> [String:Any] in
- return representable.asDictionary()
- })
- }
- }
- // Here's what I wanted to do, but can't.
- extension Array where Element == [String:Any] {
- func asType<Q:DictionaryRepresentable>() -> [Q] {
- return self.flatMap({ (dictionary) -> Q? in
- return Q.from(dictionary: dictionary)
- //Xcode says: "Cannot convert value of type 'Q.SelfType?' to closure result type '_?'"
- })
- }
- }
- // So I resorted to adding that third protocol method,
- // and at least gave it a default implementation, as seen below:
- extension DictionaryRepresentable {
- static func from(dictionaries: [[String:Any]]) -> [SelfType] {
- return dictionaries.flatMap { (dict) -> SelfType? in
- return self.from(dictionary: dict)
- }
- }
- }
Add Comment
Please, Sign In to add comment