Constraining Generic Placeholder Types

suggest change

A generic type parameter can be required to conform to a protocol, for example Equatable:

class MyGenericClass<T: Equatable> {
    var value: T
    init(value: T) {
        self.value = value
    }
}

Every MyGenericClass must use a type that conforms to Equatable, so values of that type can be compared with ==.

let ints = MyGenericClass(value: 1)        // Int conforms to Equatable
let text = MyGenericClass(value: "swift")  // String conforms to Equatable

class NotEquatable {}
// MyGenericClass(value: NotEquatable()) // error: NotEquatable does not conform to Equatable

Feedback about page:

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



Table Of Contents