Using Variables and Constants

Let’s start writing some code and get a feel for how Swift works. Start a new playground (File > New > Playground), and call it NumbersPlayground. Delete the first line that creates the string (var str = "Hello, playground"), but leave the import UIKit. The import statement pulls in iOS frameworks we almost always want to use, so we will always leave that as the first line of our playgrounds.

Computers were originally built for math, so let’s start with some simple numbers. Type the following:

 let​ foo = 1

The right pane shows a 1. This is nice and simple: we’ve created foo and assigned it the value 1, which is what’s shown in the results pane.

So far, so good. Now let’s do some math. Like many languages, Swift has a += operator to add and assign, so let’s try that.

 foo += 1

Problem! It doesn’t give us a 2! Instead, a red circle pops up in the left gutter next to our new line of code. Click the circle icon, and a red bar appears, saying:

 Left side of mutating operator isn't mutable: 'foo' is a 'let' constant

That’s bad! On the other hand, the circle icon means “instant fix,” so that’s good! When we clicked the icon, it also showed a pop-up box that looks like the following:

images/startingswift/numeric-let-assignment-error.png

The first line of the pop-up restates the error, and any subsequent lines give us instant-fix options. The error is that let creates a constant, a value that can’t change. Once we set foo to 1, we can never change it again. If we do want foo to change, it needs to be a variable. That’s what the second line is offering. In fact, it has even provisionally turned the let into a var to show us the effect of its proposed fix, as shown in the preceding figure.

This is what we want, so click the second line to accept the change to var. Now we can perform all the math on foo that we like.

Constants vs. variables might seem like a semantic difference: some languages like C make variables the default and constants uncommon, while JavaScript doesn’t have constants at all. In Swift, using constants is preferred when you know that a value should not or cannot change. This allows the compiler to make certain performance optimizations for constants. We always have to choose between marking things as constants or variables, and this is on purpose; as we’ll see again and again, many of Swift’s design choices are built on the idea of the developer being explicit about his or her intentions.

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

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