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?

2 Answers 2

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"]
}
Sign up to request clarification or add additional context in comments.

2 Comments

What if I do not know what number Ford is? Because it can be number 1, 2 and even 100.
myArray.suffixFrom(index.successor())
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"]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.