swift 4.2 官方文档学习笔记(十五)- Generics

Sellen Wei
2 min readDec 24, 2018

--

Generic Functions

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).

Type Parameters

What does T mean here? Why there is no definition of “T”, but Xcode does not have compile error?

The generic function’s name (swapTwoValues(_:_:)) is followed by the placeholder type name (T) inside angle brackets (<T>). The brackets tell Swift that T is a placeholder type name within the swapTwoValues(_:_:) function definition. Because T is a placeholder, Swift doesn’t look for an actual type called T.(<T>的含义)

You can provide more than one type parameter by writing multiple type parameter names within the angle brackets, separated by commas. Usually people use capital letters such as T, U, and V. (泛型的命名)

Generic Types(泛型的类型)

Swift enables you to define your own generic types. These are custom classes, structures, and enumerations that can work with any type, in a similar way to Array and Dictionary.

Type Constraints (类型限制,不是所有类型都可以是泛型)

It’s sometimes useful to enforce certain type constraints on the types that can be used with generic functions and generic types.

This requirement is enforced by a type constraint on the key type for Dictionary, which specifies that the key type must conform to the Hashable protocol, a special protocol defined in the Swift standard library. All of Swift’s basic types (such as String, Int, Double, and Bool) are hashable by default.(dictionary的key必须是继承hashable protocol)

以上,只有继承SomeClass的类型T和继承SomeProtocol的类型U才能被当成正确的输入类型被传入。

Associated Types

protocol里面使用的泛型,需要定义称为Associated Types,以方便他的subclass继承的时候implement

Adding Constraints to an Associated Type

Generic Where Clauses:

使用where来判断传入参数是否满足先决条件,这个虽然放在generic章节,但是我认为所有的方程都可以使用where来判断input类型是否满足要求

  • C1 must conform to the Container protocol (written as C1: Container).
  • C2 must also conform to the Container protocol (written as C2: Container). (C1,C2 必须是继承container protocol的泛型)
  • The Item for C1 must be the same as the Item for C2 (written as C1.Item == C2.Item). (C1, C2的Item不但满足equatable,而且要是有相同hash value的类型)
  • The Item for C1 must conform to the Equatable protocol (written as C1.Item: Equatable).

The first and second requirements are defined in the function’s type parameter list, and the third and fourth requirements are defined in the function’s generic where clause.

Extensions with a Generic Where Clause

在extension中使用的, 如果要使用新的泛型,比如Item,那么就要在extension里面对新的泛型进行定义,使用where关键词来对泛型的具体类型进行约束。

Associated Types with a Generic Where Clause

同样在 Associated Types 中也可以使用where对其类型进行更严格的定义

Generic Subscripts

Subscripts can be generic, and they can include generic where clauses. You write the placeholder type name inside angle brackets after subscript, and you write a generic where clause right before the opening curly brace of the subscript’s body.

--

--