Immutable variables

In the imperative programming style, values held in application variables whose contents never change are known as constants to differentiate them from variables that could be altered during execution. Examples might include a view's height and width or the value of Π to several decimal places.

Unlike programming languages such as Objective-C in which some types are mutable and some are not, Swift provides a way to create an immutable or mutable version of the same type. In Swift, we use the let and var keywords to create and store values:

  • The var keyword is used to create a variable that can be altered later, in other words, to create mutable variables
  • The let keyword is used to create a constant that cannot be altered later, in other words, immutable variables or constants

Therefore, in Swift, we do not need to have types such as NSMutableArray as opposed to NSArraym, or NSMutableDictionary as opposed to NSDictionary to differentiate between mutability and immutability. We can simply define Dictionary with var or let to make it mutable or immutable.

In addition, the Swift compiler always suggests and warns us about variables that are not changed and will be converted to constants later.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset