Alex Alex - 20 days ago 6
iOS Question

Swift 3 Iterate Over Array of Classes

I am trying to translate the following code to Swift 3. I feel like other posters have answered this, but I can't seem to figure it out.

- (BOOL)allowTouchForSubview:(UIView *)subview {
NSArray *classes = @[[UITextField class], [UISearchBar class], [UITextView class]];
for (Class class in classes) {
if ([subview isKindOfClass:class]) {
return YES;
}
if ([subview.superview isKindOfClass:class]) {
return YES;
}
};
return NO;
}


Here's what I have so far:

func allowTouchForSubview(subview: UIView) -> Bool {
let allowedClasses: [AnyClass] = [UITextField.self, UISearchBar.self, UITextView.self]
for classType in allowedClasses {
if subview is classType {
return true
}
if let superview = subview.superview {
if superview is classType {
return true
}
}
}
return false
}


It errors on both references to
classType
and says 'use of undeclared type classType'. What is going on here?

Answer

Try this:

    func allowTouchForSubview(subview: UIView) -> Bool {
         let allowedClasses: [AnyClass] = [UITextField.self, UISearchBar.self, UITextView.self]

    for classType in allowedClasses {
        if subview.isKind(of: classType)  || (subview.superview?.isKind(of: classType) ?? false) {
            return true
        }
    }
    return false 
}

to test:

let test = UITextView()
allowTouchForSubview(subview: test)//prints true

let textField = UITextField()
allowTouchForSubview(subview: textField)//prints true


let subview = UIView()
allowTouchForSubview(subview: subview) //prints false
test.addSubview(subview)
allowTouchForSubview(subview: subview) //prints true