No more textField.text ?? “”

MdNiks
1 min readJun 28, 2019

--

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)

}

Console Image

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

Console Image

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.

--

--

MdNiks

I'm an accomplished iOS programmer with more than 12 years of experience working in a collaborative environment with tight deadlines.