Swift Unwrapping Optionals Tutorial

preview_player
Показать описание
Check out my new full length iOS course:

In this tutorial we will learn how to safely unwrap optionals in Swift 4 and learn how to avoid force casting as well as discuss the nil coalescing operator. It is very important to learn how to write safe Swift code because force unwrapping is a very dangerous game to play.

If you are new to iOS development and would like to learn from a more in depth course make sure to check out my iOS Development Fundamentals Course below which contains 20 video tutorials and over 3 hours of video tutorial content where we build an app from scratch.
--
50% off iOS Development Fundamentals Course on Udemy:

or use CODEPRO999 for 50% off the course price.

--

Useful Learning Resources

--

Check out some of the apps I've built:

--

Follow Code Pro on:

If you found this tutorial helpful please like the video, share the video, and subscribe to CodePro. You can follow CodePro on Twitter, Facebook, for the latest channel news and updates.
Рекомендации по теме
Комментарии
Автор

Force unwrapping / force casting is a very dangerous game to play in Swift and usually leads to crashes. One of the biggest features in swift is optional values and the ability to safely unwrap optional values. However, if we force unwrap or force cast optionals in our code then we lose all the defensive benefits Swift provides and end up with unsafer code.

CodePro
Автор

Great tutorials. Yours is the first to mention the "??" operator for optional nil case. You're a life saver!

michaelnajera
Автор

Very useful tutorial. Clearly explains different ways to unwrap optionals and instantly made me a better Swift developer.

benmonty
Автор

Hello Code Pro, I very new to this coding. So I"m getting stuck on these optionals also and I thought this little exercise might help me. Here's a little code that I was trying learn when a textfield hasn't any text.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var button: UIButton!
var text = String()

@IBAction func buttonPressed(_ sender: UIButton) {
text = String(textField.text!)
textLabel.text = text
if textField != nil {
textLabel.text = text
} else {
textLabel.text = "0"
textField.text = "0"
}
}
}

When running code and entering numbers in textfield the label will show the right numbers. But when I don't enter anything in textfield both label and textfield remain empty. The good thing is its not crashing. Any help would be awesome if you have the time, thank you.

hermdetector