Use generics to enhance type-safety
suggest changeTake this example without generics. TestObject and myJson are assumed in the first call.
protocol JSONDecodable {
static func from(_ json: [String: Any]) -> Any?
}
The protocol declaration seems fine unless you actually use it.
let myTestObject = TestObject.from(myJson) as? TestObject
Why do you have to cast the result to TestObject? Because of the Any return type in the protocol declaration.
Generics avoid that cast, which can fail at runtime:
protocol JSONDecodable {
associatedtype Element
static func from(_ json: [String: Any]) -> Element?
}
struct TestObject: JSONDecodable {
static func from(_ json: [String: Any]) -> TestObject? {
return nil
}
}
let testObject = TestObject.from(myJson) // testObject is now automatically `TestObject?`
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents