-3

I need to search an array of objects for a specific value.
Is there a functionality in swift equivalent to for(Distance d : distances) in Java.

0

2 Answers 2

1

Are you referring to for-in loop?

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

for distance in distances {
    if distance == something {
        // do something
        break
    }
}

Hope it helps!

Sign up to request clarification or add additional context in comments.

Comments

0

You can use something like below

let arr = [1,2,3,4,5]
let index = arr.firstIndex(of: 3)

the index will give the first index of the matching object. There are other variations to it. Check here for more details https://developer.apple.com/documentation/swift/array/1848165-first

Update: Specific to your query

struct Test {
    let number: Int
}

let arr = [Test(number: 1),Test(number: 2),Test(number: 3),Test(number: 4),Test(number: 5)]
let index = arr.firstIndex(where: {$0.number == 4 })

the index will give the first index of the matching object.

2 Comments

How would I go about implementing this for an int inside an object as my array is of objects
@chad updated the answer with your specific question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.