Swift
Beginner
1 min read
Basic Types and Collections
Example
// Arrays
var fruits: [String] = ["apple", "banana", "cherry"]
fruits.append("date")
fruits.insert("avocado", at: 0)
print(fruits.count) // 5
print(fruits[1]) // banana
// Array operations
let doubled = fruits.map { $0.uppercased() }
let filtered = fruits.filter { $0.count > 5 }
let joined = fruits.joined(separator: ", ")
// Dictionaries
var scores: [String: Int] = ["Alice": 95, "Bob": 87]
scores["Charlie"] = 92
scores.updateValue(90, forKey: "Bob")
for (name, score) in scores {
print("\(name): \(score)")
}
// Sets
var uniqueTags: Set<String> = ["swift", "ios", "mobile"]
uniqueTags.insert("apple")
let hasSwift = uniqueTags.contains("swift")
// Set operations
let a: Set = [1, 2, 3, 4]
let b: Set = [3, 4, 5, 6]
print(a.union(b)) // {1,2,3,4,5,6}
print(a.intersection(b)) // {3,4}