In project a lot of time, we do unwrapped stuff for textFields. Please find below problem which we face in routine developer life.
UITextFields.text returns an optional string. so when you try to use it, you have to unwrap it or provide a default value.
let textFields = UITextField()
textFields.text = “Niks here”
let defaultText = textFields.text
if let unwrappedText = textFields.text {
print(unwrappedText)
}
Solution : Extensions to the rescue!
Here i have create an extensions property for UITextField that will return the unwrapped string, or default empty string.
extension UITextField {
var stringVal: String {
return self.text ?? “”
}
}
Utilisation : And you can use like this !
let stringValUsingExt = textFields.stringVal
Just use it. w00t! How cool is that and all done with just
a few lines of code!
If you have any comments or questions, please respond below! I’d love to hear from you.