โ—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)

Last updated