Swift Tutorial menu

Swift Loops and Collections

Loops run code many times, and collections hold many values together.

for-in Loops

A for-in loop goes through a range or a collection:

Example

swift
for i in 1...3 {
    print("Round \(i)")
}

for i in 0..<3 {
    print(i, terminator: " ")
}
print()

for i in stride(from: 10, to: 0, by: -3) {
    print(i, terminator: " ")
}
print()
Output
Round 1
Round 2
Round 3
0 1 2 
10 7 4 1 

If you do not need the counter, use _: for _ in 1...3 { print("Hi") }.

while and repeat-while

while checks the condition first. repeat-while runs the code once and then checks.

Example

swift
var balance = 1000
var months = 0
while balance < 1500 {
    balance += 200
    months += 1
}
print("Saved \(balance) in \(months) months")

var tries = 0
repeat {
    tries += 1
} while tries < 3
print("Tries: \(tries)")
Output
Saved 1600 in 3 months
Tries: 3

Use break to stop a loop and continue to skip to the next round.

Arrays

An array is an ordered list of values of the same type. Use var if you want to change it.

Example

swift
var fruits = ["Mango", "Apple", "Banana"]
print(fruits[0])
print(fruits.count)

fruits.append("Guava")
fruits.remove(at: 1)
print(fruits)

for fruit in fruits {
    print("I like \(fruit)")
}

for (index, fruit) in fruits.enumerated() {
    print(index, fruit)
}
Output
Mango
3
["Mango", "Banana", "Guava"]
I like Mango
I like Banana
I like Guava
0 Mango
1 Banana
2 Guava

Indexes start at 0. Asking for an index that does not exist (like fruits[10]) crashes the program, so check count first.

Dictionaries

A dictionary stores key: value pairs. Looking up a key gives an optional, because the key may not exist.

Example

swift
var marks = ["Ali": 85, "Ayesha": 92]
marks["Bilal"] = 74

print(marks["Ayesha"] ?? 0)
print(marks["Zara"] ?? 0)
print(marks.count)

for name in marks.keys.sorted() {
    print("\(name): \(marks[name]!)")
}
Output
92
0
3
Ali: 85
Ayesha: 92
Bilal: 74

Dictionaries have no fixed order. If you need the items in order, sort the keys as in the example above. Here ! is safe because each key came from the dictionary itself.

Sets

A set stores unique values with no order. It is good for checking if something exists.

Example

swift
var visited: Set = ["Karachi", "Lahore", "Karachi"]
print(visited.count)
visited.insert("Quetta")
print(visited.contains("Lahore"))
print(visited.contains("Multan"))
Output
2
true
false

Choosing a Collection

CollectionOrdered?Duplicates?Use it for
ArrayYesAllowedA list of items in order
DictionaryNoKeys uniqueLooking up a value by key
SetNoNot allowedUnique items, fast checks

Exercise

Exercise

Which line adds "Peach" to the end of the array var fruits = ["Mango"]?

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