도래울

Loop through subview to check for empty UITextField - Swift 본문

개발/iOS

Loop through subview to check for empty UITextField - Swift

도래울 2016. 7. 13. 09:16
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.


Update for Swift 2: 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
    }
}


Comments