Constraining Generic Placeholder Types
suggest changeA 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents