Beginner’s guide to Swift arrays

[ad_1]

An array can hold multiple elements of a given type. We can use them to store numbers, strings, classes, but in general elements can be anything. With the Any type you can actually express this and you can put anything into this random access collection. There are quite many ways to create an array in Swift. You can explicitly write the Array word, or use the [] shorthand format. 🤔



let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

let strings = ["a", "b", "c"]

let anything: [Any] = [1, "a", 3.14]


let empty = Array<Int>()
let a: Array<Int> = Array()
let b: [Int] = [Int]()
let d = [Int](repeating: 1, count: 3)
let e = Array<String>(repeating: "a", count: 3)


The Array struct is a generic Element type, but fortunately the Swift compiler is smart enough to figure out the element type, so we don’t have to explicitly write it every time. The Array type implements both the Sequence and the Collection protocols, this is nice because the standard library comes with many powerful functions as protocol extensions on these interfaces.


let array = [1, 2, 3, 4]


print(array.isEmpty) 
print(array.count) 
print(array.contains(2)) 
print(array[0]) 
print(array[1...2]) 
print(array.prefix(2)) 
print(array.suffix(2)) 




Above are some basic functions that you can use to get values from an array. You have to be careful when working with indexes, if you provide an index that is out of range your app will crash (e.g. anything smaller than 0 or greater than 4 for the sample code). 💥


Working with collection types can be hard if it comes to index values, but there are some cool helper methods available. When you work with an array it’s very likely that you won’t use these methods that much, but they are derived from a lower layer and it’s nice to have them.



let array = [1, 2, 3, 4]


print(array.startIndex) 
print(array.endIndex) 
print(array.indices) 
print(array.startIndex.advanced(by: array.count)) 
print(array.firstIndex(of: 3) ?? "n/a") 
print(array.firstIndex { $0 > 3 } ?? "n/a") 
print(array[array.startIndex.advanced(by: 1)]) 
print(array.index(after: 2))


print(array.index(before: 2))


print(array.index(array.startIndex, offsetBy: 2, limitedBy: array.endIndex) ?? "n/a")


We can also manipulate the elements of a given array by using the following methods. Please note that these methods won’t alter the original array, in other words they are non-mutating methods.


let array = [1, 5, 2, 3, 2, 4]


print(array.dropLast(2)) 
print(array.dropFirst(2)) 
print(Array(array.reversed())) 
print(Array(Set(array))) 
print(array.split(separator: 2)) 
for index in array.indices {
    print(array[index]) 
}


for element in array {
    print(element) 
}


for (index, element) in array.enumerated() {
    print(index, "-", element) 
}


There are mutating methods that you can use to alter the original array. In order to call a mutating method on an array you have to create it as a variable (var), instead of a constant (let).


var array = [4, 2, 0]


array[2] = 3
print(array) 
array += [4]
print(array) 
array.replaceSubrange(0...1, with: [1, 2])
print(array) 
let element = array.popLast() 
print(array) 
array.append(4)
print(array) 
array.insert(5, at: 1)
print(array) 
array.removeAll { $0 > 3 }
print(array) 
array.swapAt(0, 2)
print(array) 
array.removeFirst()
print(array) 
array.removeLast()
print(array) 
array.append(contentsOf: [1, 2, 3])
print(array) 
array.remove(at: 0)
print(array) 


One last thing I’d like to show you are the functional methods that you can use to transform or manipulate the elements of a given array. Personally I use these functions on a daily basis, they are extremely useful I highly recommend to learn more about them, especially map & reduce. 💪


let array = [1, 5, 2, 3, 2, 4]


print(array.sorted(by: <)) 
print(array.sorted { $0 > $1 }) 
print(array.first { $0 == 3 } ?? "n/a") 
print(array.filter { $0 > 3 }) 
print(array.map { $0 * 2 }) 
print(array.map(String.init).joined(separator: ", ")) 
print(array.allSatisfy { $0 > 1 }) 
print(array.reduce(0, +)) 
print(array.reduce(false) { $0 || $1 > 3 }) 
print(array.reduce(true) { $0 && $1 > 1 }) 


As you can see arrays are quite capable data structures in Swift. With the power of functional methods we can do amazing things with them, I hope this little cheat-sheet will help you to understand them a bit better. If you have questions feel free to reach me on Twitter. 😉





[ad_2]

Source link

Leave a Reply

Your email address will not be published.