Skip to content

Commit fa20808

Browse files
committed
Examples 09-13
1 parent 6126bbd commit fa20808

File tree

6 files changed

+569
-104
lines changed

6 files changed

+569
-104
lines changed

contents/[09]arrays/index.md

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,151 @@ description: ""
44
order: 9
55
---
66

7+
An array is a collection that holds values in a specific order.
8+
9+
Arrays in Swift can store values of any standard data type, including `String`, `Int`, `Double`, and `Bool`. Swift's type inference makes it easy to create arrays without explicitly specifying their types:
10+
11+
```swift
12+
// Array of String elements, type inferred
13+
let names = ["Kitti", "Tibi", "Havoc"]
14+
15+
// Array of Int elements, explicit type annotation
16+
let integers: Array<Int> = [1, 2, 3]
17+
18+
// Array of Double elements, short type syntax
19+
let doubles: [Double] = [2.6, 3.4, 4.8]
20+
21+
// Array of Bool elements, type inferred
22+
let booleans = [true, false]
23+
24+
// Array of String elements, empty array
25+
let empty: [String] = []
26+
```
27+
28+
We can even create an array by using a range or repeating an element:
29+
30+
```swift
31+
let smallNumbers = Array(0...10)
32+
33+
let helloArray = Array(repeating: "hello", count: 10)
34+
```
35+
You can easily check whether an array is empty, see how many items it holds, and grab elements by their index. Swift lets you access the first and last items, look up the valid index range, and even pick a random element. You can also find out if an array includes a certain value or get the index of a specific item:
36+
37+
```swift
38+
let numbers = [42, 7, 13, 99, 5]
39+
40+
// Checks if the array contains no elements
41+
print(numbers.isEmpty)
42+
43+
// Returns the total number of elements in the array
44+
print(numbers.count)
45+
46+
// Retrieves the element at a specific index position
47+
print(numbers[0])
48+
print(numbers[1])
49+
print(numbers[2])
50+
51+
// Provides the valid index range for the array
52+
print(numbers.indices)
53+
54+
// Accesses the first and last elements, respectively
55+
print(numbers.first!)
56+
print(numbers.last!)
57+
58+
// Returns a set number of elements from the start or end
59+
print(numbers.prefix(2))
60+
print(numbers.suffix(2))
61+
62+
// Selects a random element from the array
63+
print(numbers.randomElement()!)
64+
65+
// Checks if a specific value exists in the array
66+
print(numbers.contains(13))
67+
print(numbers.contains(100))
68+
69+
// Returns the index of an element, or nil if not found
70+
print(numbers.firstIndex(of: 7)!)
71+
72+
// Returns the smallest and largest values in the array
73+
print(numbers.min()!)
74+
print(numbers.max()!)
75+
```
76+
77+
To modify an array, it must be declared as a variable using the `var` keyword, since constant arrays cannot be changed. These functions allow you to update, add, or insert elements when working with mutable arrays:
78+
79+
```swift
80+
// Updates the element at a specific index
81+
var dailyActivities = ["Eat", "Repeat"]
82+
dailyActivities[1] = "Sleep"
83+
84+
// Adds a single element to the end of the array
85+
dailyActivities.append("Yoga")
86+
87+
// Adds multiple elements to the end of the array
88+
dailyActivities.append(contentsOf: ["Rest", "Repeat"])
89+
90+
// Concatenates another array to the end of the array
91+
dailyActivities += ["Rest", "Repeat"]
92+
93+
// Inserts an element at a specified position in the array
94+
dailyActivities.insert("Learn", at: 0)
95+
dailyActivities.insert("Drink", at: dailyActivities.count)
96+
```
97+
98+
Swift provides plenty of ways to remove elements from an array, such as removing the first item, removing the last item, removing at a specific index or removing a range of elements:
99+
100+
```swift
101+
// Removes the first N elements from the array
102+
dailyActivities.removeFirst()
103+
dailyActivities.removeFirst(2)
104+
105+
// Removes the last N elements from the array
106+
dailyActivities.removeLast()
107+
dailyActivities.removeLast(2)
108+
109+
// Removes the element at a specific index
110+
dailyActivities.remove(at: 2)
111+
112+
// Removes a range of elements from the array
113+
dailyActivities.removeSubrange(2...3)
114+
115+
// Removes all elements from the array
116+
dailyActivities.removeAll()
117+
```
118+
119+
These mutating functions modify the original array:
120+
121+
```swift
122+
// Swaps the elements at the specified indices
123+
dailyActivities.swapAt(0, 2)
124+
125+
// Reverses the order of the elements in the array
126+
dailyActivities.reverse()
127+
128+
// Sorts the elements of the array in ascending order
129+
dailyActivities.sort()
130+
131+
// Randomly shuffles the elements in the array
132+
dailyActivities.shuffle()
133+
```
134+
135+
Non-mutating functions always return a new array. In Swift, there are both mutating and non-mutating versions of functions like `sort()` and `sorted()`. This naming convention helps you know which functions change the original array and which do not.
136+
137+
138+
```swift
139+
let numbers = [42, 7, 13, 99, 5]
140+
141+
// Sorted array
142+
let sortedNumbers = numbers.sorted()
143+
144+
// Reversed collection
145+
let reversedNumbers = numbers.reversed()
146+
147+
// Shuffled array
148+
let shuffledNumbers = numbers.shuffled()
149+
```
150+
151+
Non-mutating functions leave the original array unchanged. This means you can use them on constant values, since they do not modify the original array but instead give you a new one.
152+
153+
154+

contents/[10]sets/index.md

Lines changed: 87 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,46 +4,108 @@ description: ""
44
order: 10
55
---
66

7+
In Swift, a Set is a collection type that stores unique values of the same type in _no particular order_. Unlike arrays, sets don't allow duplicate values, and since they don't preserve the order of elements, we call them unordered collections. Also, in some cases, sets are faster than arrays. There are several ways to create sets:
78

8-
foo
9+
```swift
10+
// using the full syntax
11+
let set1: Set<String> = []
12+
// using the short syntax
13+
let set2 = Set<String>()
14+
// using type inference
15+
let set3: Set = ["A", "B"]
16+
```
17+
18+
Note that duplicate values are automatically removed when creating a set. You can also check set properties and access elements in ways similar to arrays, such as verifying if the set is empty, counting its elements, or retrieving a random element:
919

1020
```swift
11-
let x = 5
12-
let y = 5
13-
var z = 0
21+
let numbers: Set<Int> = [1, 2, 3, 2, 1]
1422

15-
z = x + y // addition
16-
print(z) // => 10
23+
// Check if the set is empty
24+
print(numbers.isEmpty)
1725

18-
z = x - y // subtraction
19-
print(z) // => 0
26+
// Get the number of elements in the set
27+
print(numbers.count)
2028

21-
z = x * y // multiplication
22-
print(z) // => 25
29+
// Get a random element from the set
30+
print(numbers.randomElement()!)
31+
```
32+
You can insert elements into a set, remove specific elements, remove any element, or clear all elements. You can also check if a set contains a particular value:
2333

24-
z = x / y // division
25-
print(z) // => 1
34+
```swift
35+
var roles: Set = ["view", "edit"]
2636

37+
// Add a new element to the set
38+
roles.insert("manage")
2739

28-
var x = 10
40+
// Remove an exact element from the set
41+
roles.remove("edit")
2942

30-
x += 2 // addition
31-
print(x) // => 12
43+
// Remove the first element from the set
44+
roles.removeFirst()
3245

33-
x -= 2 // subtraction
34-
print(x) // => 10
46+
// Remove all elements from the set
47+
roles.removeAll()
3548

36-
x *= 2 // multiplication
37-
print(x) // => 20
49+
// Check if a specific element exists in the set
50+
print(roles.contains("view"))
51+
```
52+
53+
Sets don’t preserve order, but you can sort them into an array:
54+
55+
```swift
56+
var numbers: Set<Int> = [21, 34, 54, 12]
3857

39-
x /= 2 // division
40-
print(x) // => 10
58+
let ascendingNumbers = numbers.sorted()
59+
print(ascendingNumbers)
60+
61+
let descendingNumbers = numbers.sorted(by: >)
62+
print(descendingNumbers)
4163
```
4264

43-
bar
65+
They also support fast set operations:
66+
67+
```swift
68+
let first: Set = [1, 2, 3, 5]
69+
let second: Set = [0, 2, 3, 4]
70+
71+
// Combine all unique elements from both sets
72+
print(first.union(second))
4473

45-
```sh
46-
swift main.swift
74+
// Find elements present in both sets
75+
print(first.intersection(second))
76+
77+
// Get elements in 'first' that are not in 'second'
78+
print(first.subtracting(second))
79+
80+
// Find elements that are in either set, but not both
81+
print(first.symmetricDifference(second))
4782
```
4883

49-
baz
84+
Relationship checks are also built in:
85+
86+
```swift
87+
let a: Set = [1, 2]
88+
let b: Set = [1, 2, 3, 4]
89+
90+
// Check if all elements in 'a' are also contained in 'b'
91+
print(a.isSubset(of: b))
92+
93+
// Check if 'b' contains every element in 'a'
94+
print(b.isSuperset(of: a))
95+
96+
// Check if 'a' and another set share no common elements
97+
print(a.isDisjoint(with: [5, 6]))
98+
```
99+
100+
Sets are sometimes faster than arrays for membership checks and set operations because they use hash-based storage, allowing for constant-time lookups and modifications.
101+
102+
103+
104+
105+
106+
107+
108+
109+
110+
111+

0 commit comments

Comments
 (0)