Skip to content
Educora
Beginner15 min2 / 14

Constants, variables, types and strings

Store values with `let` and `var`, learn Swift's basic types and type inference, and put values into strings with interpolation.

Check yourself
In this lesson you will learn
  • Declare constants with let and variables with var and explain the difference
  • Recognise the types Int, Double, String and Bool and 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”.

Swift
let birthYear = 2012
var score = 0
score = 10
score += 5
print(birthYear)
print(score)
Expected output
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:

Swift
let city = "Baku"
city = "Ganja" // error: cannot assign to value: 'city' is a 'let' constant
This code does not compile.

Types and type inference

In Swift every value has a type, and a type never changes. These are the most common types:

TypeWhat it storesExample
Intwhole numbers42, -7
Doublenumbers with a decimal part3.14, 1.62
Stringtext"Baku"
Charactera single character"A"
Boola logical value: true or falsetrue, false
Definition
Type inference

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.

Swift
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))
Expected output
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.

Swift
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) + "!")
Expected output
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.

Swift
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).")
Expected output
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.

Swift
let word = "Swift"
print(word.count)
print(word.uppercased())
print(word.lowercased())
print(word.hasPrefix("Sw"))
print(word.contains("if"))
print("".isEmpty)
Expected output
5
SWIFT
swift
true
true
true

For text over several lines, use three double quotes ("""). Interpolation works in such text too:

Swift
let student = "Elvin"
let card = """
Student: \(student)
City: Baku
"""
print(card)
Expected output
Student: Elvin
City: Baku
1 / 5

Key points

  • let declares a constant, var a variable; use let wherever you can.
  • The basic types are Int, Double, String, Character and Bool.
  • 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.

1 / 10
Which keyword declares a name whose value will never change?