How to use optional binding in Swift 2

I'm new to learning Swift, so I decided that I could also learn Swift 2. Everything still made sense to me, except for the following code snippet. Hope someone can shed some light on this for me.

//: Playground - noun: a place where people can play import UIKit //Works let possibleNumber="2" if let actualNumber = Int(possibleNumber) { print("\'\(possibleNumber)\' has an integer value of \(actualNumber)") } else { print("could not be converted to integer") } //Doesn't Work and I'm not sure why let testTextField = UITextField() testTextField.text = "2" let numberString = testTextField.text //I know this is redundant if let num = Int(numberString) { print("The number is: \(num)") } else { print("Could not be converted to integer") } 

The top of the code is straight from the Apple Swift 2 ebook, and it makes sense to me how it uses an optional binding to convert a string to int. The second part of the code is basically the same, except that the line comes from the text property of UITextField. The bottom of the code gives the following error:

Playground execution failed: / var / folders / nl / 5dr8btl543j51jkqypj4252mpcnq11 / T /./ lldb / 843 / playground21.swift: 18: 18: error: value of optional type 'String?' does not unfold; you wanted to use '!' or '?'? if let num = Int (numberString) {

I fixed the problem using this line:

 if let num = Int(numberString!) { 

I just want to know why a second example is needed! and the first is not. I am sure the problem is that I am getting a string from a text field. Thanks!

+5
source share
1 answer

The difference is that in the first case, possibleNumber not an optional variable. This is definitely a string. It cannot be nil.

In the second case, textField.text returns an optional string and therefore numberString is an optional variable. It could be zero.

Now ... Conversion Int("") returns an optional int. if the string is "abc", then it cannot return a number, so it returns nil. This is what you deploy with the if let... .

However, in the second case, your string is also optional, and Int () does not accept an optional parameter. So you force it to unfold. This is dangerous, as it can cause the application to crash if the string is zero.

Instead, you can do it ...

 if let numberString = textFeidl.text, number = Int(numberString) { // use the number } 

This first expands the text, and if available, use it. Get the number. If it is not zero, you enter a block.

In Swift 2, you can also use the guard let function.

Just saw that you are using Swift 2.

You can do it the same way ...

 func getNumber() -> Int { guard let numberString = textField.text, number = Int(numberString) else { return 0 } return number } 
+7
source

All Articles