Swift Tutorial menu

Swift Variables and Data Types

Variables and constants store values so your program can use them later.

let and var

KeywordCreatesCan change?
leta constantNo
vara variableYes

Example

swift
let name = "Ali"
var score = 70
score = 85
print("\(name) scored \(score)")
Output
Ali scored 85

Writing name = "Bilal" would give an error, because name is a constant.

Use let whenever the value does not need to change. Xcode even warns you when a var is never changed.

Type Inference and Annotations

Swift works out the type from the value. This is called type inference. You can also write the type yourself with a colon. This is a type annotation.

Example

swift
let city = "Karachi"          // inferred as String
let population: Int = 20000000
let rate: Double = 278.5
var isOpen: Bool = true
isOpen = false
print(city, population, rate, isOpen)
Output
Karachi 20000000 278.5 false

Once a variable has a type, it cannot hold a different type. A String variable can never store a number.

Data Types

TypeStoresExample
IntWhole numbers25
DoubleDecimal numbers (high precision)3.75
FloatDecimal numbers (less precision)3.75
Booltrue or falsetrue
StringText"Hyderabad"
CharacterOne character"A"

A Character also uses double quotes, but you must write the type: let grade: Character = "A".

Type Conversion

Swift never mixes types by itself. Int plus Double is an error. Convert one of them first:

Example

swift
let pens = 3
let pricePerPen = 25.5
let total = Double(pens) * pricePerPen
print(total)

let rounded = Int(total)
print(rounded)

let label = "Pens: " + String(pens)
print(label)
Output
76.5
76
Pens: 3

Int(76.5) cuts off the decimal part. It does not round.

Converting Text to Numbers

Turning a string into a number may fail, for example Int("hello"). So Swift gives back an optional, which is either a number or nil (no value). You will learn optionals properly in the conditions lesson. For now, ?? gives a default value:

Example

swift
let input = "42"
let number = Int(input) ?? 0
print(number + 8)

let bad = Int("abc") ?? 0
print(bad)
Output
50
0

Naming Rules

  • Names can contain letters, numbers and underscores, but cannot start with a number
  • Use camelCase: studentName, totalPrice
  • Names cannot be Swift keywords such as let or class

Exercise

Exercise

Why does let x = 5 + 2.5 work, but let a = 5; let b = 2.5; let c = a + b fails?

Learn Swift with a teacher

Join the App Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp