Algorithmic Vision | Learning | Coding

iOS Development 05: Generic

Don’t Care Type

泛型代码让你能根据自定义的需求,编写出适用于任意类型的、灵活可复用的函数及类型。

Basic Grammar

Generic Function

The generic version of the function uses a placeholder type name (called T, in this case) instead of an actual type name (such as Int, String, or Double).

T can be any name.

The actual type to use in place of T is determined at each time the generic function is called.

func genericFunction<T>(_ a: T, _ b: T) {
    ...
    ...
}

Generic Types

struct Stack<Element> {
    var items: [Element] = []
    mutating func push(_ item: Element) {
        items.append(item)
    }
    mutating func pop() -> Element {
        return items.removeLast()
    }
}

var stackOfStrings = Stack<String>()

Type Constraint

虽然泛型能够使得函数和自定义类型支持任何类型的数据类型。 不过,如果能对泛型函数或泛型类型中添加特定的类型约束,将在某些情况下非常有用。 类型约束指定类型参数必须继承自指定类、遵循特定的协议或协议组合。