• Home
  • What is ?
  • DSA
  • MAD
  • Concept
  • Practice
  • Misc
  • Quiz
  • YT
  • Home
  • What is ?
  • DSA
  • MAD
  • Concept
  • Practice
  • Misc
  • Quiz
  • YT
  • #News
  • #APPS
  • #Events
    • #WWDC
    • #I/O
    • #Ignite
  • #Let’s Talk
  • #Interview
  • #Tips

MyCodeTips mycodetips-newlogocopy1

  • Home
  • What is ?
  • DSA
  • MAD
  • Concept
  • Practice
  • Misc
  • Quiz
  • YT
Swift

Optionals in Swift ( ! ? )

What Is an Optional

Optionals in Swift , The underlying concept of an optional is easy to grasp. An optional acts as a container for a value of a particular type. The container holds a value or it doesn’t. Type safety is a cornerstone of the Swift language. As a result, variables and constants need to be initialized before they can be accessed.

Swift is a very safe language, by which I mean it works hard to ensure your code never fails in surprising ways. One of the most common ways that code fails is when it tries to use data that is bad or missing

A regular variable must contain a value. Example: String must contain a string, even if that string is empty, i.e. “”. It cannot be nil.
An optional variable might contain a value, or might not. It must be unwrapped before it is used. Example: String? might contain a string, or it might contain nil. The only way to find out is to unwrap it.

An implicitly unwrapped optional might contain a value, or might not. But it does not need to be unwrapped before it is used. Swift won’t check for you, so you need to be extra careful. Example: String! might contain a string, or it might contain nil – and it’s down to you to use it appropriately. It’s like a regular optional, but Swift lets you access the value directly without the unwrapping safety. If you try to do it, it means you know there’s a value there – but if you’re wrong your app will crash.

Declaring Optionals

To declare an optional, we use a question mark. In the following example, we declare an optional of type String? or optional String. The question mark indicates that we are dealing with an optional.

Here’s an optional Integer declaration −

var mycodetipsInt: Int?

Here’s an optional String declaration −

var mycodetipsStr: String?

Declaration is equivalent to explicitly initializing it to nil which means no value −

var mycodetipsStr: String? = nil

var mycodetipsString:String? = nil

if mycodetipsString != nil {
   print(mycodetipsString)
} else {
   print("This String has nil value")
}

Output : This String has nil value

Forced Unwrapping

Optionals in Swift lets you override its safety by using the exclamation mark character: !. If you know that an optional definitely has a value, you can force unwrap it by placing this exclamation mark after it. If you defined a variable as optional, then to get the value from this variable, you will have to unwrap it. Putting an exclamation mark at the end of the variable.

var mycodetipsString:String?

mycodetipsString = "Hello, Swift !"

if mycodetipsString != nil {
   print( mycodetipsString! )
} else {
   print("mycodetipsString has nil value")
}

Outout : Hello, Swift !

if you try this on a variable that does not have a value, your code will crash.

Optional should never be forced unwrapped unless you are absolutely certain it contains a value.

Automatic Unwrapping

You can declare optional variables using an exclamation mark instead of a question mark. Such optional variables will unwrap automatically and you do not need to use any further exclamation mark at the end of the variable to get the assigned value.

var mycodetipsString:String!

mycodetipsString = "Hello, Swift !"

if mycodetipsString != nil {
   print(mycodetipsString)
} else {
   print("mycodetipsString has nil value")
}

Unwrapping Optionals

Because the value of an optional is wrapped in a container, you cannot access the value of an optional like you access the value of a variable or constant.

let mycodetipsbody: String = message

The above statement will generate an error. Xcode’s suggestion a try by adding an exclamation mark after the name of the optional.
But what happens if the optional has no value?

var message: String?
let mycodetipsbody: String = message!

When the optional message doesn’t contain a value, an error is thrown. By appending an exclamation mark at the end of an optional, the optional is forced unwrapped. This means that we unwrap the value of the optional’s container no matter what it contains. If the optional has a value, we can read the value. If the optional’s container is empty, an error is thrown.

If you force unwraps an optional that doesn’t contain a value, your process or application terminates. Optional should never be forced unwrapped unless you are absolutely certain it contains a value.

Optional Binding

Let’s add some safety to the example. Before we assign the value of the message to the body, it is better to first check if the optional contains a value.

var message: String?

if message != nil {
    print(message!)
} else {
    print("no value found")
}

This is much safer and we avoid the error we encountered earlier. The downside is that the solution is verbose. A more common approach is to use optional binding to safely unwrap the value of the optional.

var message: String?

if let unwrappedMessage = message {
    print(unwrappedMessage)
} else {
    print("no value found")
}

Optionals in Swift inspects the value of the message and assigns the value to the unwrappedMessage constant only if the message contains a value. The unwrappedMessage constant is then available in the if clause. If the message doesn’t contain a value, the else clause is executed. The solution is still verbose, but it is easy to read and understand. Optional binding is very powerful.

var name: String? = "mycodetips"
var high: Float? = 127.00
var low: Float? = 99.23

if let name = name, let high = high, let low = low {
    print("\(name): \(high) - \(low)")
}

Happy Swift Coding 🙂

Liked it? Take a second to support Ranjan on Patreon!
Become a patron at Patreon!
  • Click to share on Reddit (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • More
  • Click to share on Pocket (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
Written by Ranjan - 1294 Views
Tags | IOS, swift, Tips & Tricks
AUTHOR
Ranjan

Namaste, My name is Ranjan, I am a graduate from NIT Rourkela. This website is basically about of what i learnt from my years of experience as a software engineer on software development specifically on mobile application development, design patterns/architectures, its changing scenarios, security, troubleshooting, tools, tips&tricks and many more.

You Might Also Like

mycodetips-newlogo2

How to use datatype in IOS or Objective-c

September 26, 2013
mycodetips-newlogo2

Tips to Loading image from a URL to UIImage object

March 10, 2014
mycodetips-newlogo2

How to Create iCal event in IOS

June 19, 2014
Next Post
Previous Post

Support us

mycodetips
mycodetips

Follow us @ LinkedIn 2850+

Subscribe for updates

Join 8,213 other subscribers

Latest Posts

  • YT-Featured-solidprinciples
    SOLID Principles of Software Design
  • IOS 16 Features
    Latest features in IOS 16
  • r-language
    How can R language be used for data analysis?
  • wordpress-coding-blog
    Guide To WordPress Coding Standards
  • YT-Featured-Algorithm
    What is Algorithm?
whiteboard

Whiteboard(PRO)

whiteboard

Whiteboard(lite)

alphabets

Kids Alphabet

techlynk

Techlynk

techbyte

Do2Day

techbyte

Techbyte

  • #about
  • #myapps
  • #contact
  • #privacy
  • #Advertise
  • #myQuestions

Android Android Studio API APP Programming Apps blogging CSS DATABASE dsa Features HTML HTML5 installation Interview Questions IOS iPhone javascript Mac objective-c OS Programming quicktips SDK SEO SQL swift Tips & Tricks Tools UI Web Wordpress Xcode

  • SOLID Principles of Software Design
  • Latest features in IOS 16
  • How can R language be used for data analysis?
  • Guide To WordPress Coding Standards
  • What is Algorithm?

©mycodetips.com