How to accept multiple types as parameter in functions?
function, ios, parameters, swift, types
Solution
You could type the parameter as `UIView`, since all the mentioned controls inherit from it.
func hide(object: UIView, duration: Double, delay: Double) {
UIView.animate(withDuration: duration, delay: delay, options: [], animations: {
object.alpha = 0
} ,
completion: nil
)
}
func show(object: UIView, duration: Double, delay: Double) {
UIView.animate(withDuration: duration, delay: delay, options: [], animations: {
object.alpha = 1
} ,
completion: nil
)
}
Problem
I wanted to create a general function in another swift file for hiding and showing UI objects with an animation. Here are both codes: ``` func hide(object: /*My UI Object*/, duration: Double, delay: Double) { UIView.animate(withDuration: duration, delay: delay, options: [], animations: { object.alpha = 0 } , completion: nil ) } func show(object: /*My UI Object*/, duration: Double, delay: Double) { UIView.animate(withDuration: duration, delay: delay, options: [], animations: { object.alpha = 1 } , completion: nil ) } ``` I want to use this function of objects like: UILabel, UIButton, UIView, UITextField and so on. I couldn't find any way allowing multiple types as the "object" parameter. I also tried setting the type of "object" to Any but this result in the error of "object" not having the member "alpha". Setting the type to AnyObject result in the error of not being able to assign to property because of "object" being a "let" constant. Thank you for your help!