Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this generic type constraint mean in Swift?

Look at the definition for the overload of += operator in Swift that lets you add elements to a collection:

/// Append the elements of rhs to lhs
func +=<T, C : Collection where T == T>(inout lhs: ContiguousArrayBuffer<T>, rhs: C)
                                ^^^^^^

What does the T == T constraint do? Why do we need it here? It looks like a trivial constraint that's always true.

like image 268
Jean-Philippe Pellet Avatar asked Jun 11 '14 14:06

Jean-Philippe Pellet


People also ask

What is generic constraints in Swift?

Generics in Swift allows you to write generic and reusable code, avoiding duplication. A generic type or function creates constraints for the current scope, requiring input values to conform to these requirements.

What is generic type constraint?

A type constraint on a generic type parameter indicates a requirement that a type must fulfill in order to be accepted as a type argument for that type parameter. (For example, it might have to be a given class type or a subtype of that class type, or it might have to implement a given interface.)

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.


1 Answers

The definitions you see in Xcode are not actually a valid Swift code. It is somehow generated on the fly from the original files

I would assume that the T == T part is a mistake done by the generator when reducing the original files.

I have tried to define a similar function by myself and T == T is not necessary there, it actually sometimes triggers a warning.

like image 157
Sulthan Avatar answered Nov 06 '22 07:11

Sulthan