โspecialize generic function
Applying constraints to individual functions
// generic function
func viewFactory<T: UIView>(numberOfView: Int) -> [T] {
return Array(repeating: T(), count: numberOfView)
}
// โ๏ธ Cannot explicitly specialize a generic function
let buttons = viewFactory<UIButton>(numberOfView: 3)
// โ
infer from return type
let buttons: [UIButton] = viewFactory(numberOfView: 3)
// โ
infer from method parameter type
func methodThatsNeedButtons(_ buttons: [UIButton]) {}
methodThatsNeedButtons(viewFactory(numberOfView: 3))
// โ
explicitly put the type parameter (T) in parameter list
func viewFactory<T: UIView>(_ t: T.Type, numberOfView: Int) -> [T] {
return Array(repeating: T(), count: numberOfView)
}
viewFactory(UIButton.self, numberOfView: 3)
Sundell โฉ Specializing protocols in Swift
Last updated