var KnowMe = Optionals❓
In today’s #knowme, we will be talking about Optionals type in Swift.Since this is my first #knowme post, I would like to talk about what 🔍knowme is.
What’s a #KnowMe post?
KnowMe posts are where I will be discussing on class / framework structure and how it was built. We will be having two major sections
- Working : Explains on how class / framework works under the hood.
- Re-Implementing : Implementing the same class with our custom code in Swift.
Now lets get to Optionals.
“Every great developer you know got there by solving problems they were unqualified to solve until they actually did it.” — Patrick McKenzie
Under the Hood
We all have read posts and Apple documentation about Optionals, that explains about how to use them in Swift , unwrapping , optional binding , optional chaining and Nil-Coalescing. Yes, we are not gonna cover those here, have you ever wondered how to create your own Optional type? or what are Optionals made of?. Then this post is for you. Lets see whats an Optional type under the hood.
Optionals type is a enum.Yes, you heard it right. Optionals are enums that has two cases some and none. This explains how we get to use optionals to carry a nil value. To see how optionals are structured, we take to build it one by one.Lets first create a enum with some and none case.
Now we have the enum but how can you associate this enum with a data.Well you use the concept of associated values in enum to store a data.Let revisit the enum and make those changes.
Now we can do something like this to store string in KSOptional.
We have created a enum that accepts a value, now lets change the way its involved. Optionals in swift can be initialized, to make it initializable we create convenience init for enum and also make sure enum can accept any object by using Generics.
Now we can use KSOptional like,