Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between print(nil) and print(name) when var name: String? = nil

I’m a student who’s new in Swift.

While I’m studying about the Optional, I got curious about the keyword nil, so I tried some experiment with it. I’m using the Swift version 5.5.

As you can see in the image below, if I assign nil to a optional variable (which I named ‘name’) and then print it with print(name) and print("(name)") (string interpolation), I got nil on the console in both cases. (Line 5, 9)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But when I print nil without the optional variable, which I printed it with print(nil) and print("(nil)"), I got an error on both cases. (Line 7, 11)

Various ways to print nil in Swift
enter image description here

I expected them all to print out nil but they didn’t.
I really want to know the difference between those cases.

>Solution :

Interesting question actually. If you look at the Swift documentation:

Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”.

So think of it as nil is the absence of some value. As an example if you have:

var name: String?

name can either be a string value, or the absence of a string value.

So it makes no sense to try and print nil explicitly since you already know that it’s the absence of a value, however, it makes sense to print name to check if it has a value and in that case what it is, or if it has no value.

The print function is telling you that you never just want to work with nil, and it makes no sense to print it explicitly, so the compiler prevents you from doing it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading