Image made with https://imgflip.com/ Have you ever struggled with the various “?” and “!” symbols here and there in a Swift code? Or ever found yourself confused about the phrases like “forced unwrapping”, “optional binding”, “nil coalescing”, “implicit binding” or “optional chaining”? You’re in the right place! Optionals are a powerful feature in Swift language which come to solve the problem of non-existing values. Coming from Java and being passed through the hell of NPEs, I’m truly excited with this feature of Swift. Image credit www.raywenderlich.com What are optionals and why we need them? is just a type in Swift language, nothing fancy. and (optional Int) are two different types, if your variable happens to be of type you can be absolutely sure it will always have an integer value, and if your variable is of type it will either have an integer value or it will have no value at all (in other words, it will be ). Optional Int Int? Int Int? nil Think of as a wrapper type. It’s like a gift box which wraps the value inside, and like a real-life box, can either contain something or be empty. optional optional An optional which contains integer value of four, as if to write let myOptional: Int? = 4 An optional that doesn’t contain any value, as if to write let myOptional: Int? = nil The high level idea of wrapping the value inside a box is that we can safely use the box without worrying what’s inside. There’s a powerful functional programming concept behind Swift optionals - the . I highly recommend to delve deeper and study monads so you can have a bigger picture of what is this all about. At the end I’ll provide some good sources to start with. monads Under the hood types are merely an enum with two cases — meaning no value is set and meaning the value is set and it’s the value associated with it. optional None Some Forced Unwrapping Ever seen this annoying compiler error when trying to perform some “innocent” operation? At first glance you’re not doing anything wrong, just trying to add two integer numbers, just the first one is an but it surely has an integer value, so why compiler keeps complaining? optional Well, because compiler doesn’t know how to add a box into an integer. In order to achieve this we need to the optional, in other words we need to open the box and extract the value inside. For that we put the “!” mark after the variable’s name meaning “I’m sure this box contains something, extract that value and use it”. This is called It’s generally a “dangerous” thing to do because if the box is empty the app will crash at runtime. A good practice is to check for before unwrapping. unwrap forced unwrapping. nil Under the hood is just a switch statement. forced unwrapping Optional Binding Like is a way of opening the box, but it does the job more cleverly and with less pollution than . It allows to check the and extract its value into a constant or variable as part of a single action. It’s useful when we need to use the unwrapped value many times in the body. forced unwrapping, optional binding forced unwrapping optional if This will be read as “If the has a value, extract that value into the and use it inside of the body, otherwise print that it’s nil”. Note that we didn’t use “!” with , that’s because it represents the already unwrapped value of . So we just unwrap it once and can use it multiple times in the body. optionalInt constantInt if constantInt optionalInt if Under the hood works similar to the , except in this case it just breaks the switch instead of throwing an exception. optional binding forced unwrapping Implicitly Unwrapped Optionals Sometimes we’re really-really sure we’ll always have a value in our optional just after it’s set the first time. In this case there’s no need to unwrap the optional every time we want to use it, because it’s safe to assume we have a value. come to help in this case, it’s sort of saying “unwrap this guy once and use the value anywhere you want”. Implicitly unwrapped optionals are declared with the “!” mark in their type. So for the implicitly unwrapped String optional we would have as its type. Implicitly unwrapped optionals String! Note that we’re not using the “!” mark with the , because it’s an . assumedInt implicitly unwrapped optional Nil coalescing Sometimes we want to use a default value when the optional is nil. Let’s take a look at this example: This could be reduced to a one line by using a ternary operator (the “?” below represents the ternary operator). Nil coalescing allows us to shorten this even more. This just means “If is then use zero, otherwise use its unwrapped value”. optionalInt nil Optional Chaining is a feature that allows to call properties and methods on an optional that might currently be nil. Unlike which would result in a runtime exception, fails gracefully when the optional is nil. Optional chaining forced unwrapping optional chaining Let’s take a look at this example: a person may or may not have a bank account, and a bank account surely has a balance. So if we want to get the balance for a person’s bank account we might need to first check if he/she has a bank account or not, and in case of positive answer get its balance. Here’s where and the idea of using the box without opening it come into play. optional chaining Instead of putting “!” to unwrap the , we put “?” after it to say “If the person has bank account then go ahead and get its balance, if the is , just return as its ”. Because of this, the result of is always an . So essentially allowed us not to worry about what’s inside the box called . If the box is empty, we get an empty box as a result, and if the box has a value, we get the expected result wrapped into another box. bankAccount bankAccount nil nil balance optional chaining optional optional chaining bankAccount In summary are not that scary, are they? We just learned that they represent a wrapper type, that they’re like a box wrapping a value, and the box can be opened in 3 different ways Optionals (hey, I’m sure the box is not empty, please open it, and in case I was wrong just punish me by crashing my app) forced unwrapping (hey, I’m not sure what’s inside the box, open it carefully and if it’s empty, just don’t perform anything with it) optional binding i_mplicitly unwrapped optionals_ (hey, I’m sure I’ll have a value once it’s set the first time, I don’t want to bother unwrapping it everywhere in my code)We learned that we can have a very concise way of using default values in case of empty box due to . And finally we learned about the . We learned that we not always need to open the box in order to use it, and that’s the whole beauty of . I didn’t go deep into that topic to talk about and , because it will complicate things for beginners (for whom this article is generally targeted), but now when you understand how to deal with I strongly encourage you to go deeper. There’re some really great sources at the bottom. nil coalescing optional chaining optionals map flatmap optionals, References and useful sources : by Matteo Manferdini. Absolutely recommend to read this short book. You can also subscribe to get Matteo’s other useful guides and articles by email. References Swift programming language guide The complete guide to understanding Swift Optionals Developing iOS 9 Apps with Swift — Stanford university course : Sources for understanding optionals as monads Swift Functors, Applicatives, and Monads in Pictures Brian Beckman: Don’t fear the Monad Some great Quora answers The Power Of Map And FlatMap Of Swift Optionals If you have any questions or feedback please don’t hesitate to post them, I will be glad to answer your questions or get your valuable feedback. Have a great time learning Swift!