I've seen some code that uses constraints like <T: Any>
and can't find the difference in the docs between that and not specifying a constraint. Is there any difference at all, like restricting to non optionals?
Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
Object, you'll apply constraints to the type parameter. For example, the base class constraint tells the compiler that only objects of this type or derived from this type will be used as type arguments. Once the compiler has this guarantee, it can allow methods of that type to be called in the generic class.
The constraint is indeed redundant, as all types are subtypes of Any
(including Optional
).
Internally, the compiler actually models the type Any
as being a protocol composition type
(e.g P1 & P2
) consisting of zero protocols. There's no way to spell this in the language, which is why Any
isn't defined in the standard library anymore1, it's just a keyword that's parsed as a type.
So the constraint T : Any
is literally interpreted as "T
must conform to all of the protocols in this empty list of protocols", which is quite evidently a redundant constraint. Really the compiler ought to warn on it (I have actually started working on a patch to do so – aiming to open a pull request sometime this week all things going well).
1. Any
used to be defined in the standard library as a typealias
for protocol<>
, when protocol compositions were spelt protocol<P1, P2>
rather than P1 & P2
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With