-
Book Overview & Buying
-
Table Of Contents
Swift Functional Programming - Second Edition
By :
So far, have to made functions, methods, and types Generic. Can we make protocols Generic too? The answer is no, we cannot, but protocols support a similar feature named associated types. Associated types give placeholder names or aliases to types that are used as part of the protocol. The actual type to use for an associated type is not specified until the protocol is adopted. Associated types are specified with the associatedtype keyword. Let's examine the following example:
protocol CustomView {
associatedtype ViewType
func configure(view with: ViewType)
} This protocol defines a configure method that takes any item of the ViewType type. This protocol does not specify how the items in the CustomView should be configured or what type they should be. The protocol only specifies a configure method that any type must provide to be considered a CustomView.
Any type that conforms to the CustomView protocol should be able to specify the type of view that it...