WTF is an Optional ?

Long story short, it helps you with the turning nothingness into somethingness, or at least simulates a sort of nothingness.

In most languages out there like C#, if a variable does not get initialized with a value or is not set to any value, it’s value is “null”. Knowing this, you can go about your life as programmer knowing that you just have to check if that variable is null before using it, and your good 😎

However with Swift that is simply not the case.  That is due to the fact that the Swift language does not allow variables to be “null” (In Swift its “nil”) at runtime. It believes that every variable has to have some sort of value. To combat this Optionals came into existence. What Optionals do when Swift asks them if a variable is “nil’, is reply with a “maybe, who knows” and Swift moves on.

Literally speaking here Optionals are just a offshoot of your standard variable that may or may not contain a value. This way your never left wonder why something didn’t have a value, when you thought it would.

Heres a coding example shown below:

var Cat:String? //<- the "?" is what just made Cat a optional
Cat = "Phil Knight"
let nowUnwrapped = Cat! //"!" <- How you can tell Swift to demand a real answer from the optional
// Swift -> what is your real name cat ?
// the technical term for this is called optional unwrapping
// Optional Binding – How you can check that your optional actually holds somthing before you start using it
if let UnwrappedString = Cat { // assigning a tempory variable that only exists for this if statment
// then you can you can use it however you like if it actually holds a value
print("the cats real name is \(UnwrappedString)")// case where it actually holds a value
} else {
print("guess the cats name was just nil") // case where it does not hold a value
}

view raw
Optionals.swift
hosted with ❤ by GitHub

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s