I am a beginner of Swift for iOS development, and want to find an elegant way to loop through an array from the second element.
If it is in Objective-C, I think I ca
you can also use custom subscript to make sure you avoid crashing
extension Array {
subscript (gurd index: Index) -> Array.Element? {
return (index < self.count && index >= 0) ? self[index] : nil
}
}
use example:
let myarray = ["a","b","c","d","e","f","g","h"]
for i in -15...myarray.count+20{
print(myarray[gurd: i])
}
if array.count>=2 {
for n in 1...array.count-1{
print(array[n]) //will print from second element forward
}
}
In general, there is a nice pattern for getting a sub-array like this:
let array = [1, 2, 3, 4, 5]
array[2..<array.count].forEach {
print($0) // Prints 3, 4, 5 (array from index 2 to index count-1)
}
Leo's answer is more succinct and a better approach for the case you asked about (starting with the second element). This example starts with the third element and just shows a more general pattern for getting arbitrary ranges of elements from an array and performing an operation on them.
However, you still need to explicitly check to make sure you are using a valid range to avoid crashing as you noted, e.g.:
if array.count > 1 {
array[2..<array.count].forEach {
print($0)
}
}
You can use your array indices combined with dropfirst:
let array = [1,2,3,4,5]
for index in array.indices.dropFirst() {
print(array[index])
}
or simply:
for element in array.dropFirst() {
print(element)
}