0

I was reading the Swift book published by Apple. According to the book:

var possibleString: String? = "an optional string"
var assumedString: String! = "an implicitly unwrapped optional string"

what's the difference between these two? And when should each one be used? It turns out both can even be set to nil.

Milad
  • 1,239
  • 3
  • 19
  • 37
  • try to use the vars in code (both should have nil value), to print them for example, in first case it won't crash because it's not implicitly unwrapped, for second it would because it's trying to unwrap a nil value – nsinvocation Jan 19 '16 at 10:07
  • 1
    Also read this: [What does an exclamation mark mean in the Swift language?](http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language?lq=1) – Eric Aya Jan 19 '16 at 10:24

3 Answers3

1

Introduce another variable into your code:

var string: String

And then observe:

string = possibleString

The code above will fail with:

Value of optional type 'String?' not unwrapped, did you mean to use '!' or '?'?

However:

string = assumedString

works.

assumedString is automatically, or implicitly unwrapped for you. Use implicitly unwrapped optionals where you are certain that the optional contains a value.

Vatsal Manot
  • 17,695
  • 9
  • 44
  • 80
0

use the first one when you cannot guaranty that there will be a string value when accessing the parameter. use the second when you are 100% sure that there is a string value in this parameter when accessing it: for example, a username field parsing before sending it to validation on the server side, when you disable the login button press if this field is empty. so it means that if the login button was pressed, you have a string value in the text field, so it is guarantied to NOT to be nil.

p.s. in swift 2, use let and not var if your value will not be changed later...

Yonatan Vainer
  • 453
  • 5
  • 15
0

From Apples Swift programming guide:

  1. var possibleString: String? = "an optional string"

Optional is value is either contains a value or nil value to indicate the that the value is missing.

While using you have to use if and let together, as

var newString : String
if let possibleString = possibleString {
newString = possibleString
}

2. var assumedString: String! = "an implicitly unwrapped optional string"

An implicitly unwrapped optional is similar to optional types but we can use it like a non optional value each time when it is accessed.

In this case you can use it directly as

var newString : String
newString = possibleString
Aruna Mudnoor
  • 4,795
  • 14
  • 16