Doug Smith
Doug Smith

Reputation: 29326

How do I pass a class as a parameter in Swift?

I want to write a function with the below signature:

func viewHasSuperviewOfClass(view: UIView, superclass: AnyObject.Type) -> Bool {
    return view.superview is superclass
}

But it won't compile. What am I doing wrong? How do I pass the superclass and treat it as a parameter?

Upvotes: 0

Views: 72

Answers (1)

vacawama
vacawama

Reputation: 154711

Pass the superclass as AnyClass and use isKind(of:) to test it:

func viewHasSuperviewOfClass(view: UIView, superclass: AnyClass) -> Bool {
    return view.superview?.isKind(of: superclass) ?? false
}

Since view.superview is an optional you need to unwrap it. Using optional chaining will return nil if there is no superview, so use the nil coalescing operator ?? to return false if there is no superview.


Example:

let button = UIButton()
let label = UILabel()
label.addSubview(button)

viewHasSuperviewOfClass(view: button, superclass: UILabel.self)  // true
viewHasSuperviewOfClass(view: label, superclass: UIButton.self)  // false

It will read a little better if you make the function signature this:

func view(_ view: UIView, hasSuperviewOfClass superclass: AnyClass) -> Bool {
    return view.superview?.isKind(of: superclass) ?? false
}

// example call
view(button, hasSuperviewOfClass: UILabel.self)

Upvotes: 1

Related Questions