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.
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
// 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.