user3064923 February 2016

What is the difference between 2 strings initilization in swift given below

String 1:

var string1=String()

String 2:

var editTag: String!

Answers


Kenneth Bruno February 2016

The top one declares and creates an instance of String.

The bottom declares an implicitly-unwrapped optional variable which can hold a String but doesn't create an instance of String.

Because the bottom is an optional it has a value of nil until it contains an instance of the class. By implicitly unwrapping it with a ! you make a promise that it will be filled with an instance, usually in the init function or similar. Because of this there's no need to check if it's filled or unwrap it before using it.


Paulw11 February 2016

The first line declares a string variable and initialises it with an empty string.

The second line also declares a string variable but in this case it is an implicitly unwrapped variable. At this point the variable is not actually initialised and any attempt to access it would produce an "unexpectedly found nil" exception.

Declaring a variable in this way allows you to not initialise the variable in the initialiser function (which normally you would have to do). You might use this when you are going to initialise a variable in a function such as viewDidLoad or provide a value from another view controller's prepareForSegue method.


Chirag kukreja February 2016

The first one will create a n instance for string, like alloc init in objective c. The second one will declare unwrapped version of string but there will be no instance of this string and accessing this variable when there is no value in this string ,it will crash.

Post Status

Asked in February 2016
Viewed 2,293 times
Voted 11
Answered 3 times

Search




Leave an answer