総称型(ジェネリクス)は山括弧で囲んで記述します。

func repeatItem<Item>(item: Item, numberOfTimes: Int) -> [Item] {
    var result = [Item]()
    for _ in 0..<numberOfTimes {
        result.append(item)
    }
    return result
}
repeatItem("knock", numberOfTimes:4)

関数およびメソッドと同様に、クラス、列挙型、構造体についても総称型にできます。

// Swift 標準ライブラリのオプショナル型を再実装
enum OptionalValue<Wrapped> {
    case None
    case Some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)

型名の後に where を置いて必要条件のリストを指定します。例えば、プロトコル実装の型や、2 つの型が同じであること、特定のスーパークラスを持つクラスなどの条件があります。

func anyCommonElements <T: SequenceType, U: SequenceType where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, _ rhs: U) -> Bool {
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                return true
            }
        }
    }
    return false
}
anyCommonElements([1, 2, 3], [3])
EXPERIMENT
2 つの数列 (sequence) に共通の値を配列として返す関数を作成するよう anyCommonElements(_:_:) 関数を変更してみよう。

<T: Equatable> と記述することは、<T where T: Equatable> と記述することと同じになります。


Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.