user2924482
user2924482

Reputation: 9140

Swift: difference in the way to unwrapp an option variable

Can some explain what is the difference between this two ways of unwrapping a variable:

version 1 :

let myVariable : String? = "my name"

let myNameVariable : String = myVariable!

version 2:

let myVariable : String? = "my name"

let myNameVariable : String! = myVariable

I'll really appreciate if some one explain the difference between those two ways of unwrapping a variable

Upvotes: 1

Views: 88

Answers (1)

Leo
Leo

Reputation: 24714

About version 1

let myVariable : String? = "my name"

let myNameVariable : String = myVariable!

This is called unwrapping, unwrap from optional type. So here type of myNameVariable is String

About version 2

let myVariable : String? = "my name"

let myNameVariable : String! = myVariable

I do not think this is unwrapping, it is about type conversion, So here type of myNameVariable is String!

It is same as

 let myNameVariable = myVariable as String!

Update: Main difference

Example 1

let myVariable : String? = "my name"

var myNameVariable = myVariable!

//myNameVariable = nil //Error

var implUnwrapVar:String! = myVariable

implUnwrapVar = nil//OK

Example 2

let myVariable : String? = nil

//var myNameVariable = myVariable! //error

var implUnwrapVar:String! = myVariable // ok

Upvotes: 1

Related Questions