Why using implicit unwrap or force unwrap letting the app crash at some stage not beneficial?
Sure. There any many proper uses of force-unwrapping where a crash will only occur early in development because a mistake has been made and once fixed, the crash won't ever happen again.
A common example is accessing an image from the resource bundle. A line such as:
let imagePath = Bundle.main.path(forResource: "image", ofType: "png")!
should crash in early development if the developer forgot to target image.png
properly. Once targeted properly, that line won't crash so there's no reason to deal with an optional path.
Other common examples are outlets. They are usually made implicitly unwrapped because by the time they are used in the view controller's code, they will have been attached. A crash probably means the outlet wasn't connected properly. It gets fixed and there's no more worry. No need to deal with guards or other optional checking.
Last example (there are many more possibilities). When dequeuing a cell from a table view, force-cast the resulting cell to the custom cell type. No need for a guard. I see code here all the time that uses a guard with as?
to throw a fatal error if the cast fails. Just force-cast. You get the same crash with less code. Once the table view and storyboard are correct, the force-cast won't fail.
Having said this, newer Swift developers should avoid the !
character on their keyboard for a while. Knowing when to safely use it is a learned skill.
If the potential crash is fully in the control of the developer and the crash could only happen because the developer make a mistake, then using !
may be appropriate.
If the potential crash can be caused by unexpected data (JSON parsing, user input, etc.), then never use !
. Code defensively in those cases.
tl;dr - yes, there are plenty of cases where forced-unwraps, forced-casts, and implicitly unwrapped variables are the correct choice.
Is it safe to force unwrap an optional after checking it is not nil
The difference between if
and guard
is just simple, but in your case, you should use if
, not guard
. guard
should be used when some values are expected to be present for the function to execute as intended. You don't want error
to be present, but if it is not nil
, you have to return
. So you should use if let
:
if let error = error {
print(error)
return
}
This way, you don't need to use force unwrapping and it improves how your code is represented.
Back to your question "In general, is this force unwrapping thread safe or not?", assuming that you are really talking about thread safety, it is certainly thread safe. Closure variables are immutable.
If you are talking about safety (ie will "fatal error: unexpectedly found nil while unwrapping an Optional value" occur), it is also certainly safe. error
must not be nil
before you can unwrap it (because of guard
), so the force unwrapping is safe.
In conclusion, your current code is bulletproof, but using if let
might be better.
Swift Optionals and Forced Unwrapping
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
what is the difference between ? and ! operator in swift?
An optional type can be nil
var nameOfToy: String?
The toy may have a name;
nameOfToy = "Buzz"
so
print (nameOfToy!)
is Buzz.
The question mark indicates that it is optional, i.e. can be nil, so you have to UNWRAP it with the !. This is because the variable is optional.
But what happens if there is no name of a toy, and you use !. In this case you get a nasty crash.
Related Topics
Swift Firestore Search for Users
Skscene Becomes Unresponsive While Being Idle
Use Quick Look Inside a Swift Cocoa Application to Preview Audio Files
Swift - Encode and Decode a Dictionary [String:Any] into Plist
Swift 4: Validating Credit Card Expiration Date
How to Make Uicollectionview Reload Once It Receives Data from Firebase
Firebase Access Keys in Queryorderby
Drag a Cgrect Using Uipangesturerecognizer
Inline Kvo of a Property in Another View Controller
Remove \\U{E2} Characters from String
Swift Callkit Sometimes Can't Activate Loudspeaker After Received Call (Only Incoming Call)
Data Ranged Subscribe Strange Behavior
Displaying State of an Async API Call in Swiftui
Hovering a Modelentity in Front of Arcamera
Swift Delegate Beetween Two Vc Without Segue
Swift Firebase Storage How to Retrieve Image with Unknow Name(Nsuuid)
Using Foreach with a String Array - [String] Has No Member 'Identified'