Quantcast
Channel: Kodeco | High quality programming tutorials: iOS, Android, Swift, Kotlin, Unity, and more
Viewing all articles
Browse latest Browse all 4370

Swift Tutorial Part 1: Expressions, Variables & Constants

$
0
0
Learn how to code using Swift 3 and playgrounds!

Learn how to code using Swift 3 and playgrounds!

Welcome to our mini series on getting started with programming in Swift!

In this series, you’ll learn some of the basics of programming while working in a modern, friendly environment with the Swift programming language.

Instead of boring you with a lot of theory, we’re going to get you coding right away by using Xcode playgrounds, which are sandbox-type environments where you can run code directly without having to code an entire app.

For this tutorial, you’ll need Xcode 8, the standard development environment for macOS, available here. If you have Xcode version 7 or below, some of the code in this tutorial won’t work as expected.

Getting Started

The set of tools you use to write software is often referred to as the toolchain. The part of the toolchain into which you write your code is known as the Integrated Development Environment (IDE). Xcode is your IDE, which includes playgrounds.

You’ll use playgrounds throughout this series to practice coding, so it’s important to understand how they work. That’s what you’ll learn during the rest of this tutorial.

Creating a Playground

When you open Xcode, it will greet you with the following welcome screen:

welcome_to_xcode

If you don’t see this screen, it’s most likely because the “Show this window when Xcode launches” option was unchecked. You can also open the screen by pressing Command-Shift-1 or clicking Window\Welcome to Xcode from the menu bar.

From the welcome screen, you can jump quickly into a playground by clicking on Get started with a playground. Click on that now and Xcode will take you to a new screen:

new_playground

From here, you can name the playground and select your desired platform. The name is merely cosmetic and for your own use; when you create your playgrounds, feel free to choose names that will help you remember what they’re about.

The second option you can see here is the platform. Currently, this can be either iOS, macOS or tvOS.

The platform you choose simply defines which template Xcode will use to create the playground. Each platform comes with its own environment set up and ready for you to begin playing around with code. For the purposes of this seris, choose whichever you wish. You won’t be writing any platform-specific code; instead, you’ll be learning the core principles of the Swift language.

Once you’ve chosen a name and a platform, click on Next and then save the playground. Xcode then presents you with the playground, like so:

empty_playground

New playgrounds don’t start entirely empty but have some basic starter code to get you going. Don’t worry — you’ll soon learn what this code means.

Playgrounds Overview

At first glance, a playground may look like a rather fancy text editor. Well, here’s some news for you: It is essentially just that!

playground_features

The above screenshot highlights the first and most important things to know about:

  1. Source editor: This is the area in which you’ll write your Swift code. It’s much like a text editor such as Notepad or TextEdit. You’ll notice the use of what’s known as a monospace font, meaning all characters are the same width. This makes the code much easier to read and format.
  2. Results sidebar: This area shows the results of your code. You’ll learn more about how code is executed as you read through the series. The results sidebar will be the main place you’ll look to confirm your code is working as expected.
  3. Execution control: Playgrounds execute automatically by default, meaning you can write code and immediately see the output. This control allows you to execute the playground again. Holding down the button allows you to switch between automatic execution and manual execution modes.
  4. Activity viewer: This shows the status of the playground. In the screenshot, it shows that the playground has finished executing and is ready to handle more code in the source editor. When the playground is executing, this viewer will indicate this with a spinner.
  5. Panel controls: These toggle switches show and hide three panels, one that appears on the left, one on the bottom and one on the right. The panels each display extra information that you may need to access from time to time. You’ll usually keep them hidden, as they are in the screenshot. You’ll learn more about each of these panels as you move through the series.

Playgrounds execute the code in the source editor from top to bottom. Every time you change the code, the playground will re-execute everything. You can also force a re-execution by clicking Editor\Execute Playground. Alternatively, you can use the execution control.

You can turn on line numbers on the left side of the source editor by clicking Xcode\Preferences…\Text Editing\Line Numbers. Line numbers can be very useful when you want to refer to parts of your code.

Once the playground execution is finished, Xcode updates the results sidebar to show the results of the corresponding line in the source editor. You’ll see how to interpret the results of your code as you work through the examples in this series.

Code comments, arithmetic operations, constants and variables are some of the fundamental building blocks of any language, and Swift is no different.

Code Comments

The Swift compiler generates executable code from your source code. To accomplish this, it uses a detailed set of rules. Sometimes these details can obscure the big picture of why you wrote your code a certain way or even what problem you are solving. To prevent this, it’s good to document what you wrote so that the next human who passes by will be able to make sense of your work. That next human, after all, may be a future you! :]

Swift, like most other programming languages, allows you to document your code through the use of what are called comments. These allow you to write any text directly along side your code, which is ignored by the compiler.

The first way to write a comment is like so:

// This is a comment. It is not executed.

This is a single line comment. You could stack these up like so to allow you to write paragraphs:

// This is also a comment.
// Over multiple lines.

However, there is a better way to write comments which span multiple lines. Like so:

/* This is also a comment.
   Over many..
   many...
   many lines. */

This is a multi-line comment. The start is denoted by /* and the end is denoted by */. Simple!

You should use code comments where necessary to document your code, explain your reasoning, or simply to leave jokes for your colleagues. :]

Printing Out

It’s also useful to see the results of what your code is doing. In Swift, you can achieve this through the use of the print command.

print will output whatever you want to the debug area (sometimes referred to as the console).

For example, consider the following code:

print("Hello, Swift Apprentice reader!")

This will output a nice message to the debug area, like so:

printing

You can hide or show the debug area using the button highlighted with the red box in the picture above. You can also click View\Debug Area\Show Debug Area to do the same thing.

Arithmetic Operations

When you take one or more pieces of data and turn them into another piece of data, this is known as an operation.

The simplest way to understand operations is to think about arithmetic. The addition operation takes two numbers and converts them into the sum of the two numbers. The subtraction operation takes two numbers and converts them into the difference of the two numbers.

You’ll find simple arithmetic all over your apps; from tallying the number of “likes” on a post, to calculating the correct size and position of a button or a window, numbers are indeed everywhere!

In this section, you’ll learn about the various arithmetic operations that Swift has to offer by considering how they apply to numbers. In later parts, you see operations for types other than numbers.

Simple Operations

All operations in Swift use a symbol known as the operator to denote the type of operation they perform.

Consider the four arithmetic operations you learned in your early school days: addition, subtraction, multiplication and division. For these simple operations, Swift uses the following operators:

  • Add: +
  • Subtract: -
  • Multiply: *
  • Divide: /

These operators are used like so:

2 + 6
 
10 - 2
 
2 * 4
 
24 / 3

Each of these lines is what is known as an expression. An expression has a value. In these cases, all four expressions have the same value: 8. You write the code to perform these arithmetic operations much as you would write it if you were using pen and paper.

broken_paper

In your playground, you can see the values of these expressions in the right-hand bar, known as the results sidebar, like so:

arithmetic_operations

If you want, you can remove the white space surrounding the operator:

2+6

Removing the whitespace is an all or nothing thing: you can’t mix styles. For example:

2+6   // OK
2 + 6 // OK
2 +6  // ERROR
2+ 6  // ERROR

It’s often easier to read expressions if you have white space on either side of the operator.

Decimal Numbers

All of the operations above have used whole numbers, more formally known as integers. However, as you will know, not every number is whole.

As an example, consider the following:

22 / 7

This, you may be surprised to know, results in the number 3. This is because if you only use integers in your expression, Swift makes the result an integer also. In this case, the result is rounded down to the next integer.

You can tell Swift to use decimal numbers by changing it to the following:

22.0 / 7.0

This time, the result is 3.142857142857143 as expected.

The Remainder Operation

The four operations you’ve seen so far are easy to understand because you’ve been doing them for most of your life. Swift also has more complex operations you can use, all of them standard mathematical operations, just less common ones. Let’s turn to them now.

The first of these is the remainder operation, also called the modulo operation. In division, the denominator goes into the numerator a whole number of times, plus a remainder. This remainder is exactly what the remainder operation gives. For example, 10 modulo 3 equals 1, because 3 goes into 10 three times, with a remainder of 1.

In Swift, the remainder operator is the % symbol, and you use it like so:

28 % 10

In this case, the result equals 8, because 10 goes into 28 twice with a remainder of 8.

Shift Operations

The shift left and shift right operations take the binary form of a decimal number and shift the digits left or right, respectively. Then they return the decimal form of the new binary number.

For example, the decimal number 14 in binary, padded to 8 digits, is 00001110. Shifting this left by two places results in 00111000, which is 56 in decimal.

Here’s an illustration of what happens during this shift operation:

shift_left

The digits that come in to fill the empty spots on the right become 0. The digits that fall off the end on the left are lost.

Shifting right is the same, but the digits move to the right.

The operators for these two operations are as follows:

  • Shift left: <<
  • Shift right: >>

These are the first operators you’ve seen that contain more than one character. Operators can contain any number of characters, in fact.

Here’s an example that uses both of these operators:

1 << 3
 
32 >> 2

Both of these values equal the number 8.

One reason for using shifts is to make multiplying or dividing by powers of two easy. Notice that shifting left by one is the same as multiplying by two, shifting left by two is the same as multiplying by four, and so on. Likewise, shifting right by one is the same as dividing by two, shifting right by two is the same as dividing by four, and so on.

In the old days, code often made use of this trick because shifting bits is much simpler for a CPU to do than complex multiplication and division arithmetic. Therefore the code was quicker if it used shifting. However these days, CPUs are much faster and compilers can even convert multiplication and division by powers of two into shifts for you. So you’ll see shifting only for binary twiddling, which you probably won’t see unless you become an embedded systems programmer!

Order of Operations

Of course, it’s likely that when you calculate a value, you’ll want to use multiple operators. Here’s an example of how to do this in Swift:

((8000 / (5 * 10)) - 32) >> (29 % 5)

Notice the use of parentheses, which in Swift serve two purposes: to make it clear to anyone reading the code — including yourself — what you meant, and to disambiguate. For example, consider the following:

350 / 5 + 2

Does this equal 72 (350 divided by 5, plus 2) or 50 (350 divided by 7)? Those of you who paid attention in school will be screaming “72!” And you would be right!

Swift uses the same reasoning and achieves this through what’s known as operator precedence. The division operator (/) has a higher precedence than the addition operator (+), so in this example, the code executes the division operation first.

If you wanted Swift to do the addition first — that is, to return 50 — then you could use parentheses like so:

350 / (5 + 2)

The precedence rules follow the same that you learned in math at school. Multiply and divide have the same precedence, higher than add and subtract which also have the same precedence.

Math functions

Swift also has a vast range of math functions for you to use when necessary. You never know when you need to pull out some trigonometry, especially when you’re a pro Swift-er and writing those complex games!

Note: Not all of these functions are part of Swift. Some are provided by the operating system. Don’t remove the import statement that comes as part of the playground template or Xcode will tell you it can’t find these functions.

For example, consider the following:

sin(45 * Double.pi / 180)
// 0.7071067811865475
 
cos(135 * Double.pi / 180)
// -0.7071067811865475

These compute the sine and cosine respectively. Notice how both make use of Double.pi which is a constant Swift provides us, ready-made with pi to as much precision as is possible by the computer. Neat!

Then there’s this:

sqrt(2.0)
// 1.414213562373095

This computes the square root of 2. Did you know that sin(45°) equals 1 over the square root of 2?

Note: Notice how you used 2.0 instead of 2 in the example above? Functions that are provided by the operating systems (like sqrt, sin and cos) are picky and accept only numbers that contain a decimal point.

Not to mention these would be a shame:

max(5, 10)
// 10
 
min(-5, -10)
// -10

These compute the maximum and minimum of two numbers respectively.

If you’re particularly adventurous you can even combine these functions like so:

max(sqrt(2.0), Double.pi / 2)
// 1.570796326794897

Naming Data

At its simplest, computer programming is all about manipulating data. Remember, everything you see on your screen can be reduced to numbers that you send to the CPU. Sometimes you yourself represent and work with this data as various types of numbers, but other times the data comes in more complex forms such as text, images and collections.

In your Swift code, you can give each piece of data a name you can use to refer to it later. The name carries with it an associated type that denotes what sort of data the name refers to, such as text, numbers, or a date.

You’ll learn about some of the basic types in this part, and you’ll encounter many other types throughout the rest of this series.

Constants

Take a look at this:

let number: Int = 10

This declares a constant called number which is of type Int. Then it sets the value of the constant to the number 10.

Note: Thinking back to operators, here’s another one. The equals sign, =, is known as the assignment operator.

The type Int can store integers. The way you store decimal numbers is like so:

let pi: Double = 3.14159

This is similar to the Int constant, except the name and the type are different. This time, the constant is a Double, a type that can store decimals with high precision.

There’s also a type called Float, short for floating point, that stores decimals with lower precision than Double. In fact, Double has about double the precision of Float, which is why it’s called Double in the first place. A Float takes up less memory than a Double but generally, memory use for numbers isn’t a huge issue and you’ll see Double used in most places.

Once you’ve declared a constant, you can’t change its data. For example, consider the following code:

let number: Int = 10
number = 0

This code produces an error:

Cannot assign to value: 'number' is a 'let' constant

In Xcode, you would see the error represented this way:

constant_reassign_error

Constants are useful for values that aren’t going to change. For example, if you were modeling an airplane and needed to keep track of the total number of seats available, you could use a constant.

You might even use a constant for something like a person’s age. Even though their age will change as their birthday comes, you might only be concerned with their age at this particular instant.

Variables

Often you want to change the data behind a name. For example, if you were keeping track of your bank account balance with deposits and withdrawals, you might use a variable rather than a constant.

If your program’s data never changed, then it would be a rather boring program! But as you’ve seen, it’s not possible to change the data behind a constant.

When you know you’ll need to change some data, you should use a variable to represent that data instead of a constant. You declare a variable in a similar way, like so:

var variableNumber: Int = 42

Only the first part of the statement is different: You declare constants using let, whereas you declare variables using var.

Once you’ve declared a variable, you’re free to change it to whatever you wish, as long as the type remains the same. For example, to change the variable declared above, you could do this:

var variableNumber: Int = 42
variableNumber = 0
variableNumber = 1_000_000

To change a variable, you simply assign it a new value.

Note: In Swift, you can optionally use underscores to make larger numbers more human-readable. The quantity and placement of the underscores is up to you.

This is a good time to take a closer look at the results sidebar of the playground. When you type the code above into a playground, you’ll see that the results sidebar on the right shows the current value of variableNumber at each line:

variables_results_sidebar

The results sidebar will show a relevant result for each line if one exists. In the case of a variable or constant, the result will be the new value, whether you’ve just declared a constant, or declared or reassigned a variable.

Using Meaningful Names

Always try to choose meaningful names for your variables and constants. Good names can acts as documentation and make your code easy to read.

A good name specifically describes what the variable or constant represents. Here are some examples of good names:

  • personAge
  • numberOfPeople
  • gradePointAverage

Often a bad name is simply not descriptive enough. Here are some examples of bad names:

  • a
  • temp
  • average

The key is to ensure that you’ll understand what the variable or constant refers to when you read it again later. Don’t make the mistake of thinking you have an infallible memory! It’s common in computer programming to look back at your own code as early as a day or two later and have forgotten what it does. Make it easier for yourself by giving your variables and constants intuitive, precise names.

Also, note how the names above are written. In Swift, it is common to camel case names. For variables and constants, follow these rules to properly case your names:

  • Start with a lowercase letter.
  • If the name is made up of multiple words, join them together and start every other word with an uppercase letter.
  • If one of these words is an abbreviation, write the entire abbreviation in the same case (e.g.: sourceURL and urlDescription)

In Swift, you can even use the full range of Unicode characters. For example, you could declare a variable like so:

var : Int = -1

That might make you laugh, but use caution with special characters like these. They are harder to type and therefore may end up causing you more pain than amusement.

bad_choice

Special characters like these probably make more sense in data that you store rather than in Swift code.

Increment and Decrement

A common operation that you will need is to be able to increment or decrement a variable. In Swift, this is achieved like so:

var counter: Int = 0
 
counter += 1
// counter = 1
 
counter -= 1
// counter = 0

The counter variable begins as 0. The increment sets its value to 1, and then the decrement sets its value back to 0.

These operators are similar to the assignment operator (=), except they also perform an addition or subtraction. They take the current value of the variable, add or subtract the given value and assign the result to the variable.

In other words, the code above is shorthand for the following:

var counter: Int = 0
counter = counter + 1
counter = counter - 1

Similarly, the *= and /= operators do the equivalent for multiplication and division, respectively:

var counter: Int = 10
 
counter *= 3  // same as counter = counter * 3
// counter = 30
 
counter /= 2  // same as counter = counter / 2
// counter = 15

Mini-exercises

If you haven’t been following along with the code in Xcode, now’s the time to create a new playground and try some exercises to test yourself!

  1. Declare a constant of type Int called myAge and set it to your age.
  2. Declare a variable of type Double called averageAge. Initially, set it to your own age. Then, set it to the average of your age and my own age of 30.
  3. Create a constant called testNumber and initialize it with whatever integer you’d like. Next, create another constant called evenOdd and set it equal to testNumber modulo 2. Now change testNumber to various numbers. What do you notice about evenOdd?
  4. Create a variable called answer and initialize it with the value 0. Increment it by 1. Add 10 to it. Multiply it by 10. Then, shift it to the right by 3. After all of these operations, what’s the answer?

Key Points

  • Code comments are denoted by a line starting with // or multiple lines bookended with /* and */.
  • Code comments can be used to document your code.
  • You can use print to write things to the debug area.
  • The arithmetic operators are:
    Add: +
    Subtract: -
    Multiply: *
    Divide: /
    Remainder: %
  • Constants and variables give names to data.
  • Once you’ve declared a constant, you can’t change its data, but you can change a variable’s data at any time.
  • Always give variables and constants meaningful names to save yourself and your colleagues headaches later.
  • Operators to perform arithmetic and then assign back to the variable:
    Add and assign: +=
    Subtract and assign: -=
    Multiply and assign: *=
    Divide and assign: /=

Challenges

Before moving on, here are some challenges to test your knowledge of variables and constants. You can try the code in a playground to check your answers.

  1. Declare a constant exercises with value 11 and a variable exercisesSolved with value 0. Increment this variable every time you solve an exercise (including this one).
  2. Given the following code:
age = 16
print(age)
age = 30
print(age)

Declare age so that it compiles. Did you use var or let?

  1. Consider the following code:
let a: Int = 46
let b: Int = 10

Work out what answer equals when you replace the final line of code above with each of these options:

// 1
let answer1: Int = (a * 100) + b
// 2
let answer2: Int = (a * 100) + (b * 100)
// 3
let answer3: Int = (a * 100) + (b / 10)
  1. Add parentheses to the following calculation. The parentheses should show the order in which the operations are performed and should not alter the result of the calculation.
5 * 3 - 4 / 2 * 2
  1. Declare two constants a and b of type Double and assign both a value. Calculate the average of a and b and store the result in a constant named average.
  2. A temperature expressed in °C can be converted to °F by multiplying by 1.8 then incrementing by 32. In this challenge, do the reverse: convert a temperature from °F to °C. Declare a constant named fahrenheit of type Double and assign it a value. Calculate the corresponding temperature in °C and store the result in a constant named celcius.
  3. Suppose the squares on a chessboard are numbered left to right, top to bottom, with 0 being the top-left square and 63 being the bottom-right square. Rows are numbered top to bottom, 0 to 7. Columns are numbered left to right, 0 to 7. Declare a constant position and assign it a value between 0 and 63. Calculate the corresponding row and column numbers and store the results in constants named row and column.
  4. Declare constants named dividend and divisor of type Double and assign both a value. Calculate the quotient and remainder of an integer division of dividend by divisor and store the results in constants named quotient and remainder. Calculate the remainder without using the operator %.
  5. A circle is made up of 2 radians, corresponding with 360 degrees. Declare a constant degrees of type Double and assign it an initial value. Calculate the corresponding angle in radians and store the result in a constant named radians.
  6. Declare four constants named x1, y1, x2 and y2 of type Double. These constants represent the 2-dimensional coordinates of two points. Calculate the distance between these two points and store the result in a constant named distance.
  7. Increment variable exercisesSolved a final time. Use the print function to print the percentage of exercises you managed to solve. The printed result should be a number between 0 and 1.

Where to Go From Here?

You can download the final playground from this part — along with the solutions for the challenges above — from this link.

In this tutorial, you’ve only dealt with only numbers, both integers and decimals. Of course, there’s more to the world of code than that! In the next part, you’re going to learn about more types such as strings, which allow you to store text.

The next part in this tutorial series deals with types and operations; once it's posted we'll provide a link right here so you can continue with your Swift adventures!

We encourage you to try the challenges above; if you find a particularly interesting solution to one of the challenges, or have any questions or comments on this tutorial, please tell us about it in the discussion below!

swift-apprentice

This tutorial was taken from Chapters 1 and 2 of Swift Apprentice, Second Edition available from the raywenderlich.com store.

The book has been completely updated to work with Xcode 8 and Swift 3. Check it out and let us know what you think!

The post Swift Tutorial Part 1: Expressions, Variables & Constants appeared first on Ray Wenderlich.


Viewing all articles
Browse latest Browse all 4370

Trending Articles