泛型术语:占位类型placeholder
Here’s a generic version of the same code:
- struct Stack<Element> {
- var items = [Element]()
- mutating func push(_ item: Element) {
- items.append(item)
- }
- mutating func pop() -> Element {
- return items.removeLast()
- }
- }
Note how the generic version of Stack
is essentially the same as the nongeneric version, but with a type parameter called Element
instead of an actual type of Int
. This type parameter is written within a pair of angle brackets (<Element>
) immediately after the structure’s name.
Element
defines a placeholder name for a type to be provided later. This future type can be referred to as Element
anywhere within the structure’s definition. In this case, Element
is used as a placeholder in three places:
- To create a property called
items
, which is initialized with an empty array of values of typeElement
- To specify that the
push(_:)
method has a single parameter calleditem
, which must be of typeElement
- To specify that the value returned by the
pop()
method will be a value of typeElement
https://docs.swift.org/swift-book/LanguageGuide/Generics.html
Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.
template<typename T>
class List
{
/* class contents */
};
List<Animal> list_of_animals;
List<Car> list_of_cars;
Above, T is a placeholder for whatever type is specified when the list is created.
https://en.wikipedia.org/wiki/Generic_programming