- Declare constants with
letand variables withvarand explain the difference - Recognise the types
Int,Double,StringandBooland convert between them - Work with string interpolation and string methods
In a game your score changes every minute, but your birth year never changes. Programs need to remember information like this too: some of it changes, some of it stays the same. Swift keeps these two cases strictly apart, and that makes programs safer.
`let` and `var`
To remember a value, we give it a name. A name declared with **let is a constant: it gets its value once and cannot be changed afterwards. A name declared with var is a variable**: you can give it a new value at any time. The = sign does not mean “equals” here, it means “store this value”.
let birthYear = 2012
var score = 0
score = 10
score += 5
print(birthYear)
print(score)2012 15
score += 5 is a short form of score = score + 5. In the same way there are -=, *= and /=. If you try to change a constant, the compiler will not run the program:
let city = "Baku"
city = "Ganja" // error: cannot assign to value: 'city' is a 'let' constantTypes and type inference
In Swift every value has a type, and a type never changes. These are the most common types:
| Type | What it stores | Example |
|---|---|---|
Int | whole numbers | 42, -7 |
Double | numbers with a decimal part | 3.14, 1.62 |
String | text | "Baku" |
Character | a single character | "A" |
Bool | a logical value: true or false | true, false |
The compiler working out a type from the value itself. When you write let age = 13, Swift figures out on its own that age is an Int. You can also state the type explicitly: let price: Double = 5.
let age = 13
let height = 1.62
let name = "Leyla"
let isStudent = true
let price: Double = 5
print(age, height, name, isStudent, price)
print(type(of: height))13 1.62 Leyla true 5.0 Double
Swift is type-safe: you cannot directly add or multiply an Int variable and a Double variable. First you convert one of them to the other's type. A conversion is written with the type's name: Double(apples), Int(7.9), String(42). Note that Int(7.9) does not round, it simply drops the fractional part.
let apples = 3
let pricePerKg = 2.5
// let total = apples * pricePerKg // error: Int * Double
let total = Double(apples) * pricePerKg
print(total)
print(Int(7.9))
print(String(42) + "!")7.5 7 42!
Strings and interpolation
Strings can be joined with +. But a handier way is interpolation: inside a string you write a backslash \ followed by a value or expression in parentheses, and it is placed into the text. Look at the example below. This way you don't have to convert numbers to strings first.
let firstName = "Aysel"
let lastName = "Mammadova"
let fullName = firstName + " " + lastName
print(fullName)
let age = 14
print("\(firstName) is \(age) years old.")
print("In 5 years she will be \(age + 5).")Aysel Mammadova Aysel is 14 years old. In 5 years she will be 19.
Strings have useful properties and methods: count gives the number of characters, uppercased() and lowercased() give the upper- and lower-case versions, hasPrefix(_:) checks how a string starts and contains(_:) checks whether it contains some part. isEmpty checks whether a string is empty.
let word = "Swift"
print(word.count)
print(word.uppercased())
print(word.lowercased())
print(word.hasPrefix("Sw"))
print(word.contains("if"))
print("".isEmpty)5 SWIFT swift true true true
For text over several lines, use three double quotes ("""). Interpolation works in such text too:
let student = "Elvin"
let card = """
Student: \(student)
City: Baku
"""
print(card)Student: Elvin City: Baku
Key points
letdeclares a constant,vara variable; useletwherever you can.- The basic types are
Int,Double,String,CharacterandBool. - Swift infers the type from the value, but you can also write it explicitly with
: Type. - Different types cannot be mixed — convert with
Double(x),Int(x),String(x). - Interpolation — a backslash and parentheses inside a string — puts any value or expression into the text.
Check yourself
10 questions. Every correct answer earns XP.