Loop through subview to check for empty UITextField - Swift

Ryan picture Ryan · Aug 2, 2014 · Viewed 24.8k times · Source

I"m wondering how to essentially transform the objective c code below into swift.

This will loop through all the subviews on my desired view, check if they are textfields, and then check if they are empty of not.

for (UIView *view in contentVw.subviews) {
    NSLog(@"%@", view);
    if ([view isKindOfClass:[UITextField class]]) {
        UITextField *textfield = (UITextField *)view;
        if (([textfield.text isEqualToString:""])) {
            //show error
            return;
        }
    }
}

Here is where i am with swift translation so far:

for view in self.view.subviews as [UIView] {
    if view.isKindOfClass(UITextField) {
        //...

    }
}

Any help would be great!

Answer

Martin R picture Martin R · Aug 2, 2014

Update for Swift 2 (and later): As of Swift 2/Xcode 7 this can be simplified.

  • Due to the Objective-C "lightweight generics", self.view.subviews is already declared as [UIView] in Swift, therefore the cast is not necessary anymore.
  • Enumeration and optional cast can be combined with to a for-loop with a case-pattern.

This gives:

for case let textField as UITextField in self.view.subviews {
    if textField.text == "" {
        // show error
        return
    }
}

Old answer for Swift 1.2:

In Swift this is nicely done with the optional downcast operator as?:

for view in self.view.subviews as! [UIView] {
    if let textField = view as? UITextField {
        if textField.text == "" {
            // show error
            return
        }
    }
}

See "Downcasting" in the Swift book.