I think that real utility arises when it is used as a limitation in a universal function of class o. This is the real code from one of my projects.
I declare the protocol with init :
protocol JSONCreatable { init(fromJson json: JSON) }
Then in the generic function, where I return a class that matches this protocol:
import SwiftyJSON extension JSON { func asObject<T>() -> T? where T: JSONCreatable { if isEmpty { return nil } return T(fromJson: self) } func asArray<T>() -> [T] where T: JSONCreatable { return array?.map{ json in T(fromJson: json) } ?? [] } }
This allows me to do things like this:
let user: User = json["user"].asObject() let results: [Element] = json["elements"].asArray()
source share