soulrain soulrain - 6 months ago 14
iOS Question

Swift optionals and if let statement

I am comparing the following code snippets:

var num = Int(numTextField.text!)!


to

if let num = Int(numTextField.text!) {}


Can someone explain to me how the if left statement doesn't need the second "!".
Does assignment in an if let block implicitly unwrap the Int optional? If it does can anyone explain the mechanisms at work?

Thanks in advance!

Answer

When you do

if let num = Int(numTextField.text!){}

It will unwrap the value for you and check if it can set the value of textfield to num. If the value is nil you will be able to handle the error like this

if let num = Int(numTextField.text!){
    print("Yes the value is not nil")
}else{
    print("Couldn't assign value to num because it's nil")
}

If you do

var num = Int(numTextField.text!)!

and the textfield is nil, you will get a runtime error and your app will crash.