In this tutorial, you are going to learn how to store a nil value to a Swift variable with the help of an example.
In Swift, you can not store nil or empty value just like any other data type in a straightforward way. This thing may be a bit tricky. Swift doesn’t have any data types for nil value. Then how we can store a nil value to a variable? In iOS app development, we may have to declare a variable without assigning any value to it.
Well, in that case, we have to go for using Swift optional. This is where optional comes in Swift to help us in this situation.
Without talking furthermore let’s start with the example:
var myInt:Int? = nil var myString:String? = "Hello"
The above code is an example of storing nil values in the variables. This is the right way to follow if you ever wish to store a nil value to a variable in Swift programming. All we have to do is just to declare it as optional by using a question mark (?).
But have you ever thought, about why we can’t do it in a straightforward way like:
var myInt:Int = nil var myString:String = "Hello"
The above code will cause a compilation error. The reason behind this I have already told you in this article. As I said earlier, Swift doesn’t have any data type for nil value.
Also, any variable in Swift must have to store some sort of data. Well, this is the purpose of using variables. Swift doesn’t accept variables with empty values. nil defines a kind of empty value.
Swift optional can help us to solve this problem. We have already seen the example of how an
optional can help us in this situation. With the optional, we can declare a Swift variable without assigning any value to it.
See the example below:
var myInt:Int? = nil
Adding a question mark in a data type like this makes it optional which means, the variable either be an integer or it can be nil.
Similarly, the below code means the variable can either be a string or can be nil:
var myString:String = "Hello"