Loop through subview to check for empty UITextField - Swift

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.


Swift 5 and Swift 4: - A Very simple answer you can understand easyly : - You can handle all kind of Objects like UILable, UITextfields, UIButtons, UIView, UIImages . any kind of objecs etc.

for subview in self.view.subviews
{
    if subview is UITextField
    {
        //MARK: - if the sub view is UITextField you can handle here
        if subview.text == ""
        {
            //MARK:- Handle your code
        }
    }
    if subview is UIImageView
    {
     //MARK: - check image
      if subview.image == nil
      {
             //Show or use your code here
      }

    }
}

//MARK:- You can use it any where, where you need it
//Suppose i need it in didload function we can use it and work it what do you need

override func viewDidLoad() {
    super.viewDidLoad()
    for subview in self.view.subviews
    {
        if subview is UITextField
        {
         //MARK: - if the sub view is UITextField you can handle here
            if subview.text == ""
            {
               //MARK:- Handle your code
            }
        }
        if subview is UIImageView
        {
          //MARK: - check image
            if subview.image == nil
                {
                 //Show or use your code here
                }
            }
        }
    }