homepage

home seiten a-z key <-- hoch --> runter home/swift/keyword/associatedtype

associatedtype

Ein zugeordneter Typ <_associated type_=""> kann verwendet werden, um ein Protokoll generisch zu machen. Er wird als generischer Typ für Eigenschaften <_properties_> genutzt. Der zugehörige Typ wird mit dem Schlüsselwort `associatedtype` angegeben.

// TYPE ist der Platzhalter für den generischen Typ
protocol Store {
    associatedtype TYPE

    var items: [TYPE] { get set }
    mutating func add(item: TYPE)
}

extension Store {
    mutating func add(item: TYPE) {
        items.append(item)
    }
}

struct Shop: Store {
    var items = [String]()
}

var shop = Shop()

shop.add(item: "Book")
shop.add(item: "Car")


Generics by Swift.org
Getting started with associated types in Swift Protocols by Antoine von der Lee, 2020
AssociatedType in Swift – A Generic Adventure by Leonardo, 2020
What is a protocol associated type? by Paul Hudson, 2019
Understanding protocol associated types and their constraints by Paul Hudson, 2018

Videos:

AssociatedType Introduction by iOS Academy, 2022, 7min


home seiten a-z <-- hoch --> rauf