Sjakelien Sjakelien - 6 months ago 17
Swift Question

What is the big deal with constants in Swift?

OK, I'm a bit late, but I finally started to look at Swift, after having programmed a lot in Objective-C.

One thing that strikes me, is the

var
and
let
thing.
As the title of this question implies, I am aware that a var is a variable, and let defines a constant.

How come this is so important? In objective-C, I hardly ever defined a constant.

Answer

'var' keyword is used to declare a variable and 'let' keyword is used to declare a constant. The value of a constant cannot be changed once it is set, whereas a variable can be set to a different value in the future. These two keywords are important because in Objective-C we have different-different classes for immutable and mutable String (NSString and NSMutableString), immutable and mutable Array(NSArray and NSMutableArray), etc. For e.g.

var str1 = "Mutable"   // In Objective-C, we use NSMutableString class for this
let str2  = "Immutable" // In Objective-C, we use NSString class for this

var arr1 = ["Mutable1", "Mutable2"]  // In Objective-C, we use NSMutableAray class for this
let arr2  = ["Immutable1","Immutable2"] // In Objective-C, we use NSArray class for this

Hope this will help you.

Comments