Swift Language Generics Use generics to enhance type-safety


Example

Let's take this example without using generics

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.

By using generics you can avoid this problem that can cause runtime errors (and we don't want to have them!)

protocol JSONDecodable {
    associatedtype Element 
    static func from(_ json: [String: Any]) -> Element?
}

struct TestObject: JSONDecodable {
    static func from(_ json: [String: Any]) -> TestObject? {
    }
}

let testObject = TestObject.from(myJson) // testObject is now automatically `TestObject?`