0
votes

I am having a hard time understanding the optionals and forced unwrapping in Swift language. I have read the book and chapters several times but I cannot understand it.

Is there a difference between the following two:

totalAmountTextField?.text.toInt()

totalAmountTextField!.text.toInt()

Also, when declaring the IBOutlets why do I always make it an optional field like this:

@IBOutlet var nameTextField :UITextField?

If I don't use the "?" at the end then it gives errors.

2
If nameTextField cannot be nil after the nib has loaded, you should think about saying @IBOutlet var nameTextField: UITextField! instead. This way you don't have to unwrap it and if the outlet gets unset in the nib, you'll get a crash rather than silent failure like you would in ObjC. - Gregory Higley

2 Answers

3
votes

totalAmountTextField?.text.toInt() is equivalent to

func foo() -> Int? { // give you optional Int
    if let field = totalAmountTextField {
        return field.text.toInt()
    } else {
        return nil // return nil if totalAmountTextField is nil
    }
}

foo()

it should be used if totalAmountTextField can be nil


totalAmountTextField!.text.toInt() is equivalent to

func foo() -> Int { // give you Int
    if let field = totalAmountTextField {
        return field.text.toInt()
    } else {
        crash() // crash if totalAmountTextField is nil
    }
}

foo()

it should be used only if you know totalAmountTextField must not be nil

0
votes
// It represents that totalAmountTextField may be nil and then stop the chain.
totalAmountTextField?.text.toInt()

// It assume that totalAmountTextField must have value, if not then caused a crash.
totalAmountTextField!.text.toInt()

You can take a look at the Swift Documentation about Optional Chaining. https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html