0

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.

john doe
  • 9,220
  • 23
  • 91
  • 167
  • possible duplicate of [What does an exclamation mark mean in the Swift language?](http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language) – rickster Aug 18 '14 at 06:25
  • 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 Jan 20 '15 at 04:52

2 Answers2

3

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

Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
  • Why must I always use ? when declaring the outlets? – john doe Aug 18 '14 at 04:00
  • thats a different question. it is because outlets must be initialized with `nil` value. you can declare it with `!`. read [this](https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/BuildingCocoaApps/WritingSwiftClassesWithObjective-CBehavior.html) – Bryan Chen Aug 18 '14 at 04:03
0
// 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

yuhua
  • 1,239
  • 8
  • 18