Oscar
Oscar

Reputation: 107

How to accept multiple types as parameter in functions?

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!

Upvotes: 3

Views: 1174

Answers (2)

adamfowlerphoto
adamfowlerphoto

Reputation: 2751

As all of these objects inherit from UIView you can use the type UIView

Upvotes: 1

Benzi
Benzi

Reputation: 2459

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

Upvotes: 8

Related Questions