1

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?

Roduck Nickes
  • 1,021
  • 2
  • 15
  • 41

2 Answers2

3

Using a Swift slice, e.g:

myArray[3...myArray.count - 1]

Output

["Lamborghini", "Ferrari", "Lada"]

Option 1

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"]
}

Option 2

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"]
}
paulvs
  • 11,963
  • 3
  • 41
  • 66
1

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"]
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253