How to get all the textfields from a view in swift

Swift: This function will return all text-fields in a view. No matter if field exists in any subview. ;-)

func getAllTextFields(fromView view: UIView)-> [UITextField] {
    return view.subviews.flatMap { (view) -> [UITextField] in
        if view is UITextField {
            return [(view as! UITextField)]
        } else {
            return getAllTextFields(fromView: view)
        }
    }.flatMap({$0})
}

Usage:

getAllTextFields(fromView : self.view).forEach{($0.text = "Hey dude!")}

Generic Way:

func getAllSubviews<T: UIView>(fromView view: UIView)-> [T] {
    return view.subviews.map { (view) -> [T] in
        if let view = view as? T {
            return [view]
        } else {
            return getAllSubviews(fromView: view)
        }
    }.flatMap({$0})
}

Usage:

 let textFields: [UITextField] = getAllSubviews(fromView: self.view)

I made it working, but still need the explanation why the code in question is not working
I got it from somewhere on the forum, not exactle able to credit the answer.

/** extract all the textfield from view **/
func getTextfield(view: UIView) -> [UITextField] {
var results = [UITextField]()
for subview in view.subviews as [UIView] {
    if let textField = subview as? UITextField {
        results += [textField]
    } else {
        results += getTextfield(view: subview)
    }
}
return results  

Call the above function in viewDidLoad or viewDidLayoutSubviews.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

/** setting bottom border to the textfield **/
    let allTextField = getTextfield(view: self.view)
    for txtField in allTextField
    {
        txtField.setBottomBorder()
    }
}