Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a generic constraint of <T: Any> and no constraint <T>

Tags:

generics

swift

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?

like image 578
Javier C Avatar asked Jun 06 '18 15:06

Javier C


People also ask

What does the generic constraint of type interface do?

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.

Where is generic type constraint?

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.

What is the purpose of the class constraints on a type parameter?

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.


Video Answer


1 Answers

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.

like image 80
Hamish Avatar answered Oct 18 '22 21:10

Hamish