There are cases where optionals may have associated optionals themselves. In this video, explore how to access these chained optionals safely and efficiently.
- [Narrator] There will definitely be times, when you need to chain optionals. In other words, unwrap an optional, that has other optional properties, associated with it. It's really handy, to think of optional chains, in a very literal sense, like a chain link. If all the links are present and strong, meaning they all have values, the chain continues. If one link fails, or is nil, the chain will break. Now, unfortunately, we're going to have to create, classes for this example, and I know we haven't covered this yet, but bear with me.
To create a class, we use the class keyword, followed by the name we want to give it. So, here, we're going to say class Adventurer. And we're going to want to want one optional property. So, var, equippedweapon, and we're going to give it a type, weapon, and it's going to be an optional. Now, we're going to get an error, because the weapon class, doesn't yet exist. So, class weapon. And here, we're just going to have on property, called name.
And this is going to be a string, for our test purposes. Now, we're going to create a constant, called newAdventurer. And it's going to be of type, Adventurer. So, we're going to initialize, a new class instance. Again, don't worry too much about this, we'll get into all this in-depth, later on. Now, let's say we want to get into the name property, of an equipped item.
Now, an equipped item is an optional, so we're going to have to chain it. So, if let weaponname, equals, newAdventurer.equippedweapon, which is an optional. And here, we're just going to add a dot, and name. What we're really doing here, is burrowing into our new adventurer class. Checking if the equipped weapon, exists or not. And if it does, accessing it's name. So, let's just print out, "You have a," and use weapon name, equipped.
Now, we're not going to see anything in our debug console, because right now, newAdventurer, does not have a weapon. The weapon is nil. So, let's catch this case, with an else statement. Print. "You're kind of useless in a fight right now." So, as far as the optional chain goes, we have a newAdventurer, which is fine, the chain is still intact. And here we get to equipped weapon.
Since it's nil, the name property can not be accessed. So, let's a weapon, to our adventurer, and se if we can change this. Newadventurer.equippedweapon, equals, an instance of our weapon class. And there we go, you have a fist, equipped. We can see that our chain unwrapping works, and we can now access the weapon's name.
- Starting new playgrounds and projects
- Variables and constants
- Writing single and multiline comments
- Core string methods
- Working with numbers
- Working with collections
- Creating arrays
- Working with sets
- Application control flow
- Writing functions
- Basic Swift classes and structs