So if I have a array that look like this:
var myArray = ["BMW", "Toyota", "Ford", "Lamborghini", "Ferrari", "Lada"]
I want to display the value inside the array after "Ford", so BMW, Toyota and Ford doesn't show up.. How can I do this?
Using a Swift slice, e.g:
myArray[3...myArray.count - 1]
Output
["Lamborghini", "Ferrari", "Lada"]
If you don't know the index of the Ford
element, find it using the indexOf
method:
if let index = myArray.indexOf("Ford") {
let startIndex = index + 1
let endIndex = myArray.count - 1
let slice = myArray[startIndex...endIndex]
let array = Array(slice)
print(array) // prints ["Lamborghini", "Ferrari", "Lada"]
}
As @leo Dabus pointed out, a much simpler method of getting the section you want from the array uses the suffixFrom
method:
if let index = myArray.indexOf("Ford") {
let slice = myArray.suffixFrom(index.successor())
let array = Array(slice)
print(array) // prints ["Lamborghini", "Ferrari", "Lada"]
}
Swift 3
You can use dropFirst
, it returns a subarray without the first N items:
let myArray = ["BMW", "Toyota", "Ford", "Lamborghini", "Ferrari", "Lada"]
let subArray = Array(myArray.dropFirst(3)) // ["Lamborghini", "Ferrari", "Lada"]
There's also indexOf
to find the first item and then get the subarray from the index:
if let index = myArray.index(of: "Ford") {
let subArray = Array(myArray.dropFirst(index.advanced(by: 1))) // ["Lamborghini", "Ferrari", "Lada"]
}