Optionals in Swift

Bob Lee
A free video tutorial from Bob Lee
iOS Instructor | Bob the Developer
5.0 instructor rating • 1 course • 1,544 students

Learn more from the full course

Learn Swift 4 with Bob: The Intermediate to Advanced Swift

Functional Programming, Protocol Oriented, Value Oriented, Generic Protocols, Object Oriented, Swift 4

17:38:08 of on-demand video • Updated September 2017

  • Learn the difference between classes and structs and which one to use
  • Learn how to create generic enums, structs, classes, protocols
  • Get a taste of functional programming with trailing, auto, and escaping closures
  • Understand how objects are created and removed through Automatic Reference Counting
  • Understand potential retain cycle in closures, delegate, and class variables
  • Understand Swift is a protocol oriented programming language
  • Apply protocols such as Equatable, Comparable, Sequence, and IteratorProtocol
  • Execute Swift files using Terminal/Command Line
  • Functional Programming
English [Auto] Walk in the very first lesson of Lauren Swift about when I start learning Swift I took courses from Linda treehouse to me her name me. I've been all there. All I wanted to do just what's become a better Albers. I just read everything that is possible within my budget. Yet there was a little problem. The most instructor The use a lot of optional those questionmark and those bangs out there but they don't really tell us why we use optional in the first place right not how you may already know how to use optional how you may already know how to unmap it but they didn't tell us why you use optional why this swift engineers implement an optional feature that is so unique compared to other programming languages out there right C++. And they don't have optional. They just have. Neal Neal but what makes it different. What why did they implement the optional in swift boat when a question does fundamental questions in this chapter and this lesson on top of them represent two rules that you must doubt when you're working with swift and throughout the entire record. Will wish were just saying remember chapter one listen to one page remember. Chapter one lesson one. Let's find out what those rules are. Let's pick it. Welcome to the very first lesson of Lauren Switchfoot about today. We're going to talk about optionals. All right. So you guys may already know how it is optional. But in this lesson we to talk about why Who why did Apple engineers or swift engineers implement this amazing feature that the freesheet from many other program languages such as Davers strip and see. OK so before we talk about optionals why arbitral came out today. I think it's important for us to go over the rules that the free sheet slit so every variable type the first rule states every variable type must be defined a type like string. It must be defined. So for example a constant name or a variable name doesn't matter name is string it's Bob. You've explicitly said hey this must be string and you have Bob and there you go. And also you can let slip in for implicity state the type of new name based on the what you enter right here. Bob the developer is obviously string now. Option click on this. You have a string right there and every variable type must define. It has to define some mind that is fine. Every other variables Define on the bottom here. And second rule says to type can infer based on the value where you will read this here of the type of new name is now being infer based on what you right here which is Bob the developer isn't string. OK. And lastly every normal type should have value associated. So what does that mean normal tined like string in double values. Now Bob here Bob the developer. So if you or two if you want to just make a variable call my name and no value associated. And you to print this thing. It's not going to work because you have to inspect every value a value has to be. You have to have you have to you have to have value for every variable constant. OK but you might wonder. All right. Or these are the rules but what are the rationales behind this implementation. Right there must be the why it's not. It's not enough to just see how this thing exists right sometimes it's important for the developers understand why these things are important and why did Apple and years made this rule. Well it's important for us to take a look at this diagram I made for you guys. This election not by the way. Let's go. Whoops. Optionals these Crucis. So if you think about programming. Program is nothing more than running a bunch of functions so when you press dead when you press the icon app icon for the first time on your app that it runs a function and that function returns a value and then runs the other function. It's like a sequence of functions that executed in sequence and in functions when folks of one starts you expect to return. For example I'm talking a very high level abstract manner. But I hope that makes sense to you slowly. So the function one returns expect functions and return int and function to takes it in value and then go through that magic and have a string and then and the function three takes that string you know so and so forth. So it's like a loop right there. The product comes off with function one and passes on it's like a factory right there that line one line to line three making iPhone. It definitely want to have some Sova a product that comes out from each line. OK. But in swift. But here's the problem. What if function one or function one is expected to return in and then function two is expected to take that INT from function one. But what if function one returns in value three one function one returns no value. Also known as Nil are either are the same thing no value or nil say no value then function to be like what I do with this and and function to try to work with something that has no value. And then eventually I don't they may return String or not and then function takes that with a value or eventually just might crash because the function too is trying to work with something that doesn't exist. So the program will crash and the best of the best stuff happens. So swift engineers have said Alright let's prevent that from happening. I don't care if if they if folks want produce a very ugly product. It doesn't matter as long as it isn't a number and their function too is able to work with that number and then provide something of value. So at least they go through our manufacturing line instead of breaking in right in the middle. So that's why you don't want to have this thing right. That's why civil engineers have said all right why now make our life easier. Why not making every single variable making every single cost to have value. Also type associated Sudan. You exactly know that this thing will eventually go through. OK. It doesn't matter how ugly the product looks like as long it's better than just breaking right in the middle because function too cannot work with something have no value. So that's why it's we've set all right let's make this thing the fault have value by default. So that's why this rules came out to be. So that's why it is also considered as a type safe language. Every variable every constant has a type associated and also has value associated. All right but so that's why it is actually a very safe language consider because there's not many problems you could have event. Well that's we live in an ideal world. But again we don't live in an ideal world. But there are times times you have to have no value. Sometimes you have to have a new value. One example is playing with social media app. So let's say you already are you're making a social media app and your app has to fetch a profile picture from Facebook or Instagram a link to it. OK. But sometimes your Facebook sometimes you the user may have a photo or associated but sometimes the user may not have a photo associated. OK. If the user has photo Raia of a certain level you have a role for the server you can take away from the database. That's good but sometimes you have no value. Right. Sometimes you have nothing. But how do you go about this. Right. Well this commonly happens. So this is not just a nonprofit example. It just happens. So now here comes optionals can it by default by normal time you're not allowed to work with no value right. Because you don't one you don't want this thing from happening. That's what you have value associated. But sometimes you need to store or some of the have new value for a variable concept. That's why we introduced optional optional is actually a byproduct of these rules. OK Sue. Oh please understand where I'm coming from. So the only the only to differentiate from the normal type the optional type. The only thing you have to do is put a question mark right there. And I'm just going to give you a lot examples. And here comes optionals. So now optional types allow storing nil nil means no value right. That's a technical term. In what if like so use just say Nil means no value. OK. So now mining put a question mark right there and is Neil. So if you attempt to call mine my name and it's going to return it's going to say Neal right here and if you print your name OK it's an optional type of string and it's going to say optional and on the bottom your optional bubbly. OK. So this is not a normal play. Just click on it. Option click on it you'll see that this is out screwing normal type. OK sounds good. OK. This is not the most important part. The most important part is why the software engineers have introduced optionals and why they'd implemented these rules in the first place. All right. If you understand these rules then they are the rationale behind optional should come out should make sense to you. OK. All right. And the things I talk about after is not as important as as to understanding why things exist. OK. And in this chord's you can talk about the why a lot. OK I like the I like to go deep anyway so I've introduced the optionals. So now that only you can store all of my names to screen a screen a not optional type. You can also have some type of int. So Bob age's Neal right there's no value. Rob ages 2:59 doesn't matter. Just random examples right. That is not only tied to string you can be an int whatever. But now if you try to do something like this do you think it's going to work. So expected you expect like one to six might come out with. But here's the thing. There are couple rules that you have to understand is that an optional rule you have to understand is optional do not interact with each other. Optional types do not interact with each other. And also you must convert optionals to normal types. And the process is called on mapping. So if you want to work with this kind of numbers you have to convert into a normal time and introduced that later. OK. So Ropp ages right now as you can see into question marks is optional in type and also then age is optional in type. So you're now at the works together. And of course if you want to change the value of RAB age feel free to you can change it any time you want as long as you make it as voire. You you should work right. He says change it right good and Ropp age still maintains as optional. OK sounds good but so now you want to work with. You want to work with optional but again you're not allowed to interact with each other so you have to convert. And there are two ways to convert. Optional type 2 normal type. OK. And the first one is call force unwrapping and I'm going to do a lot of copy pasting for such as text. And so that you know I don't waste your time. So one way to force unwrap or convert is simply putting a exclamation mark at the end. So when you say bop age exclamation mark what happens is you are comparing Ropp age is that right now is optional type right optional in type and if you are to convert it all you have to do is put a quote exclamation mark right there and you get this normal type. OK so now if you try to print new robbe age definitely just going to give you normal. There's no optional stuff just going to be printing normal. The age of 3 right Rob is three. OK. Same thing. The same thing goes to New Day and Age some nice and simple OK nice and simple. All right. That's force unwrapping or it's kind of exclamation mark right there for us. Right. And but here's the problem here's the problem. So let's say we have an image from Facebook and the user does not have the L for the profile picture. OK so you have to kind of get nil value from the database. OK. But now what happens if you try to like do something like this let normal lead normal image equals image. Exclamation mark. And what's happening here. Well why what was happening. It says unexpected found Neil while unwrapping an optional value. Well this is the example. When I first started learning I was 12. I've seen a lot of examples like this but from now on you're you don't have to worry about it. So here's the problem. Now image contains nil and you're not allowed to do this. What happens is your converting image to normal type and as you know you're not allowed to have a meal for normal type and you always have to value sociate for normal type. Doesn't matter whether to store stored in two or to a concert. Now you cannot convert nyl to normal time. And you feel valued like Bob the developer and this random value by the developer. Yes you may convert it into normal time. OK. But if you have if is nil is not going to work. Sorry not if is nil. You're not allowed to do that. OK. So the force mapping is is dangerous because if an orbital type contains a nil value you're not allowed to force and man you're going to get that where we call that unexpected error when when unwrapping error right on mapping out we call it unwrapping optional. So you don't want to do this kind of full force or mapping. There's another way call we call it implicit mapping or recall is safe unwrapping. OK. Let me introduce to the safe on mapping. Now this is a second way of unwrapping right here. So you forget about conditional Seimone will come back to you. So we have Lessie image from Facebook we have a screen name what's called about face. Are you going to have like a CPS Facebook dot com API or whatever. But for the sake of these example when it is Bob's face. OK. And then of course we can simply call image for Facebook and then just do something like that. It's easy. But as you know it but face is nil. You're not allowed to convert to normal type because you're not auto store Neil. OK. Hope that makes sense to you. But here's the thing we can say something like conditional statement if image from Facebook can is not Neil then kind of unwrap it. OK. If is Neal ignore it. Or something like that. OK. We call this it's very similar to the if else statement which unit doesn't need to know. You can say if. All right let's call it let's let's create Oh a constant call just say normal image OK. This thing called normal image. OK. Just Coston and then call it image from Facebook. Print Print normal image OK you can see elf's print. There is no image. So this is what's happening. So this is what's happening. Image from Facebook contains bobbly. You've said hey let's call this contest call normal image. And if normal image there it is there it is non-nil then just print normal image. OK. And if there is Neal then just print this there's no image there's an image. OK. We call this it's like implicit or rappings. Even if it is nil what happens is amazingly you don't you don't really get this problem when you try a nap and there's no image or safely amazingly just done nice and simple. So when it comes to unwrapping there are many times you have to unwrap. For example when whenever you call a database when you whenever you work with database when you would have you worked with API such as getting what if you don't what API means means just code written by somebody else. OK. So it is especially getting a database with the server from. From Facebook. Instagram you're using their code to get data from their database. Right. So we are using their API or their own implementation of working with server. And that's called API. It's to just API means code. OK. Code written by somebody else. So when you work with somebody is API it's definitely going to give you an optional type. And you know how to unwrap it safely. OK there are many ways to wrap it. We are also going to talk about a guard statement in later later lessons. But there are two ways. OK one is implicit in wrapping and also Forstmann mapping. And again you don't use force remapping a lot or probably you should ever avoid the force from mapping honest the Aiwass architecture just force you to do that. But most of the time you can go by doing implicit mapping using conditional statement. We also called these binding because what happens is when you when you try to get you kind of get the value out of image from Facebook and you kind of like we've you know the word binding means like sneaking into it so you created this normal image consing you kind of bind it. You can insert it. You kind of assigned a normal image we call it binding as well. OK I think I've made myself clear. And the unwrapping part is not the most important in this lesson. The most important lesson is you understand the rationals behind this rules why they came out to be why it is different for many many other programming languages. In fact in javascript which I often do a lot because I do at the moment or C or C++ what the allows you to do something like this or you don't have to define a type. You have to define the values Soozie. Right but in swithe you cannot go without matter. You have to have value and you have to have an forces type associated. And of course if you're using optional type. The only thing you have to have is the type. You can always put nil but you cannot do something like this. You cannot because nil you're not allowed to get the type of something by just putting nil. You have to have type associated. OK. Always member type has to be available for everything in swithe. And also if it's a good idea to understand the rules. Do not interact with each other you have to convert it and they're converting from normal type to optimum to normal time. It's called a mapping there are two ways to do it. Force for mapping implicit or mapping. You kind of go with this matter and in later chapters of later lessons we learn more effective ways to do unwrapping implicitly. OK. All right. That was the first lesson he has learned something new. That was too easy. That's fine. Let's see. Next lesson though. So by the way be here Bill. That means it's indicating that it's the end of each lesson. OK. Hopefully no one is annoyed by that. Some people. Does one person doesn't like that but hopefully most people find with that. OK. And this let's see if the two fundamental concepts rules in the sleep problem language. Rule number one say it's every single time whether that's at all Thorndale the type has to define whether implicitly or explicitly. Secondly there are mainly two ways to nab an optional type. The first one is you may force or not using those Bankside. Or you may safely map using it flat in the next lesson you'll discover why those questionmark an optional bangs automatically appear when you try to access a property and methods of an object. See you in that next lesson.