Chapter 3 Basics
We’ll quickly move through some of the basics of Swift.
3.1 Printing and string interpolation
We can use print
to print a value and \()
for string interpolation.
var name = "Joe"
var age = 34
print("Meet \(name). \(name) is \(age) years old")
3.2 Comments
// This is a single line comment
var notaComment = 1
/* This is a comment
that spans
multiple lines */
var notAnotherComment = 2
Single line comments are declared by putting //
at the beginning of a line.
Multi-line comments are started using /*
and ended by */
.
3.3 Basic types
The basic types in Swift are:
3.3.1 Booleans
Booleans are of type Bool
and can be either true
or false
. Anything in Swift that takes a boolean, must use a real boolean type.
Swift is strict in its treatment of boolean values. Boolean is a type that can (only) be true or false. Any operator or function that expects a boolean must be given a boolean or the type system will complain. Many dynamic languages have a much looser definition of what kind of values can be truthy (for example, in Ruby anything that not nil or false is truthy. So an empty string can be used to represent true) - if you’re coming from one of those languages you’ll have to get used to only using booleans in places where booleans are expected.
var x:Bool
x = true
var y = false
x && y // false
x || y // true
!y // true
Booleans are declared using the keyword Bool
or by initializing them with true
or false
.
3.3.2 Integers
Int
is the basic Integer type. There are also a number of Integer types of various sizes, both signed and unsigned. Listing 3.1 shows each of the Integer types along with their min and max values. For each of these types you can see their minimum and maximum values using the min
and max
properties.
Int.max // 9,223,372,036,854,775,807
Int.min // -9,223,372,036,854,775,808
UInt.max // 18446744073709551615
UInt.min // 0
Int8.max // 127
Int16.max // 32,767
Int32.max // 2,147,483,647
Int64.max // 9,223,372,036,854,775,807
The full range of Integer types are Int, UInt, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64
3.3.3 Floats and Doubles
Floating point numbers are represented using Float
and Double
, depending on the precision that you need. Floats are represented using 32bits whereas Doubles are stored using 64 bits. Doubles have precision of at least 15 decimal places, whereas Floats can have as little as 6, depending on the value. Which one you use depends on how much precision you need. Here is an example where we lose precision by assigning a Float with more decimal places than it can handle.
let piImprecise:Float = 3.14159265358979 // 3.141593
let piMorePrecise:Double = 3.14159265358979 // 3.14159265358979
3.3.4 Strings and characters
Strings and characters are represented by the String
and Character
types respectively.
By default Swift will infer that something in double quotes is a String. But if we want it to be a character we can explicitly declare it as Character
type. We can use the +
operator to concatenate two strings and we can use the Strings append
method to concatenate a character to a string.
var swif = "s" + "wif" // "swif"
var t:Character = "t" // "t"
swif.append(t) // "swift"
Both String and Character support unicode.
let pi = "\u{03c0}" // π
let r:Character = "r" // r
let squared = "\u{00b2}" // ²
var area = pi // π
area.append(r) // πr
area = area + squared // πr²
Figure 3.1 shows what the the above unicode strings look like in a playground.
Like any other basic type, strings can be either mutable or immutable - depending on whether you declare them using let or var (more on this in chapter 4).
3.4 Some basic operators
The operators for addition, subtraction, multiplication, division and modulo are similar to the ones in most c-like languages.
10 + 5 // 15
10 - 5 // 5
10 * 5 // 50
10 / 5 // 2
10 % 5 // 0
12 % 5 // 2
Assignment uses =
. Swift also has a number of compound assignment operators.
var x = 10
x += 5 // 15
x -= 5 // 10
x *= 5 // 50
x /= 5 // 10
x // 10
We can also deconstruct assignment from tuples into vars (we cover tuples in more detail in chapter 8).
var (y, z) = (20, 30)
Comparison operators are similar in Swift to those in any other c-like language.
let x = 10
x > 5 // true
x < 5 // false
x >= 10 // true
x <= 10 // true
x == 10 // true
x == 9 // false
Logical operators are stricter than you may be used to. They return a boolean and each part of the expression must evaluate to a boolean. As outlined in Section 3.3.1 these operators must be used with boolean values, and they return a boolean value.
let x = 10
x > 5 && x < 20 // true
x > 20 || x <= 10 // true
!(x < 0) // true
Swift has 2 operators for creating ranges. This is the syntax for creating a range in Swift.
1...10 // Range of 1..<11
1..<10 // Range of 1..<10
The first version (called the closed range operator) includes 10 in the range. The second version (called the half-open range operator) doesn’t include 10 in the range.
The ternary operator accepts a condition that evaluates to a boolean and then returns either the first or second branch depending on whether the initial expression was true or false.
let x = 10
x == 20 ? "Yay" : "Nay" // "Nay"
3.5 Naming things
Swift programs use camel-case for all naming. To summarize:
- CamelCase for everything
- class names and top-level constants should be capitalized (i.e.
ClassName
) - method names, function names and variable names should start with a lower-case letter (i.e.
methodName
)
In going through these examples we’ve already encountered the syntax for declaring constants and variables in Swift, although we haven’t discussed it. In the next chapter we’ll cover that in a bit more detail.