Reading — step 1 of 5
Learn
~1 min readCollections
Swift Array is ordered, growable, typed, value-semantics:
var nums = [1, 2, 3, 4]
print(nums.count) // 4
print(nums[0]) // 1
nums.append(5)
nums.removeFirst()
print(nums.contains(3)) // true
Iterate with for ... in:
for n in nums { print(n) }
for (i, n) in nums.enumerated() { print("\(i): \(n)") }
All the functional methods are there:
nums.map { $0 * 2 }
nums.filter { $0 > 2 }
nums.reduce(0, +)
nums.sorted() // returns new sorted array
nums.sorted { $0 > $1 } // descending
To declare an empty typed array: var nums: [Int] = [] or var nums = [Int](). Indexing past the end crashes — use .first, .last, or check .indices.contains(i) for safety.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…