Use generics to enhance type-safety

suggest change

Take 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?`

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents