1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
| // Arrays
var fruits: [String] = ["Apple", "Banana", "Cherry"]
print("Fruits array: \(fruits)") // Output: ["Apple", "Banana", "Cherry"]
// Adding an element
fruits.append("Date") // Output: ["Apple", "Banana", "Cherry", "Date"]
let firstFruit = fruits[0] // Output: "Apple"
// Dictionaries
var person: [String: String] = ["name": "John", "city": "New York"]
print("Person dictionary: \(person)") // Output: ["name": "John", "city": "New York"]
// Adding or updating a key-value pair
person["age"] = "30" // Output: ["name": "John", "city": "New York", "age": "30"]
// Accessing values
if let name = person["name"] {
print("Name: \(name)") // Output: "Name: John"
}
// Sets
var uniqueNumbers: Set<Int> = [1, 2, 3, 3, 4]
print("Unique numbers set: \(uniqueNumbers)") // Output: [2, 3, 1, 4]
uniqueNumbers.insert(5) // Output: [2, 3, 1, 4, 5]
// Iterating over a dictionary
print("Iterating over person dictionary:")
for (key, value) in person {
print("\(key): \(value)") // Output: name: John city: New York age: 30
}
// Collection Operations
// map
let lengths = fruits.map { $0.count } // Output: [5, 6, 6, 4]
// filter
let longNames = fruits.filter { $0.count > 5 } // Output: ["Banana", "Cherry"]
// reduce
let concatenatedFruits = fruits.reduce("") { $0 + $1 } // Output: "AppleBananaCherryDate"
let sumOfNumbers = uniqueNumbers.reduce(0) { $0 + $1 } // Output: 15
|