ジェネリクス - Swift

最終更新日: 2026-07-26

TOP(About this memo)) > 一覧(Swift) > ジェネリクス

関連型(Associated Type)

protocol Container {
    associatedtype ItemType
    mutating func append(item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}
struct IntStack: Container {
    var items = [Int]()
    typealias ItemType = Int  // 準拠させる側はtypealiasで指定。
    // 〜
}

ジェネリクス

func xxxx<T>(a: T, b: T) {
    // 〜
}
struct Stack<Element> {
    var items: [Element] = []
    mutating func push(_ item: Element) {
        items.append(item)
    }
    mutating func pop() -> Element {
        return items.removeLast()
    }
}