Sunny yue Sunny yue - 5 months ago 22
Swift Question

Why is uitextfield not outputting optional?

I printed the force unwrapped text values of my textfields in my viewdidload:

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print("loaded")
print(passwordInput.text!)
print(emailInput.text!)
}


but instead of crashing with:

loaded
fatal error: unexpectedly found nil while unwrapping an Optional value


it printed:

my console

please tell me why it didn't crash with an optional nil but "" if you know!!!

Answer Source

The default value of UITextField is an empty string. so even if you have not typed anything the value is ""

If you want to check:

if let validPass = passwordInput.text {
   print("It is not optional")
} else {
   print("It is optional")
}

And you will see that output is "It is not optional"
If you want to check whether it is empty or not:

if let validPass = passwordInput.text, !validPass.isEmpty {
    print("It is not optional or not empty")
}