In my project (written in Swift 3) I want to retrieve index of an element from array using indexOf(_:)
method (existed in Swift 2.2), but I cannot find any replacement for that.
Is there any good replacement for that method in Swift 3 or anything that act similar?
Update
I forget to mention that I want to search in custom object. In code completion I haven't got any hints when typing 'indexof'. But when I try to get index of build in type like Int
code completion works and I could use index(of:)
method.
To get the first index of an item in an array in Swift, use the array. firstIndex(where:) method. print(i1!)
To replace an element with another value in Swift Array, get the index of the match of the required element to replace, and assign new value to the array using the subscript.
Swift version: 5.6. The first() method exists on all sequences, and returns the first item in a sequence that passes a test you specify.
Access Array Elements In Swift, each element in an array is associated with a number. The number is known as an array index. We can access elements of an array using the index number (0, 1, 2 …).
indexOf(_:)
has been renamed to index(of:)
for types that conform to Equatable
. You can conform any of your types to Equatable
, it's not just for built-in types:
struct Point: Equatable { var x, y: Int } func == (left: Point, right: Point) -> Bool { return left.x == right.x && left.y == right.y } let points = [Point(x: 3, y: 5), Point(x: 7, y: 2), Point(x: 10, y: -4)] points.index(of: Point(x: 7, y: 2)) // 1
indexOf(_:)
that takes a closure has been renamed to index(where:)
:
[1, 3, 5, 4, 2].index(where: { $0 > 3 }) // 2 // or with a training closure: [1, 3, 5, 4, 2].index { $0 > 3 } // 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With