ios - What is the exact use of an Implicitly unwrapped optional String -


i couldn't understand difference between explicitly declared string , implicitly unwrapped optional string.

for example,

if initialzse string explicitly,

let assumedstring:string = "test string" print(assumedstring) 

gives output

"test string" "test string\n" 

in playground.

likewise if implicitly unwrap optional string this,

let assumedstring:string! = "test string" print(assumedstring) 

gives same output

"test string" "test string\n" 

and once use '!' while initializing, value cannot nil. can use explicit type right?

then why have use concept of using '!' (implicitly unwrapping optional string).

kindly explain difference or use of using '!' code example if possible.

in example, you're using let constants. let constants, can hardly see difference between two. situation changes.

as know, properties in class must initialized value in initializer(s). optional properties exception rule. default, nil i.e. no value.

i use implictly unwrapped optionals when have property stores view's height or ui related. declare implicitly unwrapped optionals. e.g.

var myviewsheight: cgfloat!  override func viewdidload() {     myviewsheight = self.view.viewwithtag(1).frame.height } 

you can't initialize variable in init because @ init, views have not been laid out yet! there no way know view's height. make implictly unwrapped optional because know will initialized in viewdidload. advantage of makes tracking errors easier. app crashed because if happened in viewdidload , line initializes myviewsheight not executed, know because app crashes!

you see iboutlets implictly unwrapped optionals, same reason - views can't assigned @ init.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -