Skip to content

Latest commit

 

History

History
91 lines (68 loc) · 2.74 KB

swift-keyword-associatedtype.md

File metadata and controls

91 lines (68 loc) · 2.74 KB

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


Links:

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