简体   繁体   中英

What is the exact use of an Implicitly unwrapped optional String

I couldn't understand the difference between a explicitly declared String and an implicitly unwrapped optional string.

For example,

If we initialzse a String explicitly,

let assumedString:String = "Test String"
print(assumedString)

gives the output

"Test String"
"Test String\n"

in playground.

Likewise if we implicitly unwrap an optional string like this,

let assumedString:String! = "Test String"
print(assumedString)

gives the same output

"Test String"
"Test String\n"

And also once we use '!' while initializing, then its value cannot be nil. So We can use the explicit type right?

Then why do we have to use the concept of using '!' (implicitly unwrapping an optional string).

Kindly explain the difference or the use of using '!' with a code example if possible.

In your example, you're only using let constants. With let constants, you can hardly see the difference between the two. The situation changes.

As you know, all properties in a class must be initialized to some value in the initializer(s). Optional properties is an exception to this rule. They are by default, nil ie no value.

I most often use implictly unwrapped optionals is when I have a property that stores a view's height or anything UI related. I always declare those as implicitly unwrapped optionals. eg

var myViewsHeight: CGFloat!

override func viewDidLoad() {
    myViewsHeight = self.view.viewWithTag(1).frame.height
}

You obviously can't initialize that variable in init because at init , the views have not been laid out yet! There is no way to know the view's height. You make it an implictly unwrapped optional because you know it will get initialized in viewDidLoad . Another advantage of this is that it makes tracking errors easier. Say your app crashed because if something happened in viewDidLoad and the line that initializes myViewsHeight is not executed, you will know immediately because your app crashes!

You will also see that all IBOutlet s are implictly unwrapped optionals, for the same reason - the views can't be assigned at init .

let assumedString:String = "Test String" 

Means you simply define a string constant , but when you write

let assumedString:String! = "Test String" 

means you you are declaring a string of optional type . So,it may contain a value or not . But here you are initialised at the time of declaration of string . So , If you print both will give same output. For more understanding go to below link

Difference between var someString = “Some String”, var someString: String = “Some String”, var someString = “Some String” as string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM