Difference between String! , String? and String in Swift

Rushabh Singh
2 min readMay 8, 2021

--

Let’s say we have three variables as follows,

var a : String = “Stay hungry”

var b : String! = “Stay foolish”

var c : String? = “Stay Safe”

Now let’s play with these to understand the concepts

Which of the below statements will give you compile time error???

c = a

c = b

b = a

b = c

a = b

a = c

a = nil

b = nil

c = nil

Let’s see them one by one!!!

var “c” can store “a” and “b” , no issues

c = a

c = b

var “b” can store a and “c” , all good

b = a

b = c

var “a” can store “b” , but not “c

a = b

a = c //Error : Value of optional type ‘String?’ must be unwrapped to a value of type ‘String’

Also, “b” and “c” can be set to nil but not “a”

a = nil // Error : ‘nil’ cannot be assigned to type ‘String’

b = nil

c = nil

Now let’s understand the reasons for above behaviour,

String : Represents a string, guaranteed to be present, it can’t be nil, and need to be initialised before being used

String? : Represents a string, which can be nil, and need to unwrap it

String! : Represents a string, which can be nil, and no need to unwrap it while using(implicitly forced unwrapped)

Because String! and String? both can store nil , but String cannot, hence we got errors for these statements.

a = c //Since c is optional, it may be nil, hence we need to unwrap it to resolve the above error

a = nil

Thanks for reading.

Happy coding!!!

--

--

Rushabh Singh
Rushabh Singh

Written by Rushabh Singh

Moving fast without breaking things 👨‍💻……. Exploring Mobile Apps development

No responses yet