Chapter 17: Generics
大綱
Introducing generics
Values defined by other values
什麼情況下最適合使用Generics ?
set of possible PetKind values defines the set of possible KeeperKind values
Types defined by other types
Anatomy of generic types
you can define a generic type for keepers
That Animal in angle brackets is the type parameter that specifies the type for the kind of animal you’re keeping.
you’ll encounter names like T (short for Type) from time to time, but these names should be avoided when the type parameter has a clear role such as Animal
Using type parameters
you can use type parameters such as Animal throughout your type definitions
Type constraints
the identifier Animal serves as a type parameter, which is a named placeholder for some actual type that will be supplied later.
In Swift, you do this with various kinds of type constraints.
Arrays
Array and [Element] are exactly interchangeable. So you could even call an array’s default initializer by writing Int instead of Array().
Dictionaries
To instantiate types such as Dictionary with multiple type parameters, simply provide a comma-separated type argument list:
Optionals
自定義optional type
Generic function parameters
“A function's type parameter list comes after the function name. You can then use the generic parameters in the rest of the definition.”
Key points
Generics are everywhere in Swift: in optionals, arrays, dictionaries, other collection structures, and most basic operators like + and ==.
Generics express systematic variation at the level of types via type parameters that range over possible concrete types.
Generics are like functions for the compiler. They are evaluated at compile time and result in new types which are specializations of the generic type.
A generic type is not a real type on its own, but more like a recipe, program, or template for defining new types.
Swift provides a rich system of type constraints, which lets you specify what types are allowed for various type parameters.
Last updated