Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for array's indexOf(_:) method in Swift 3

Tags:

ios

swift3

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.

like image 958
krlbsk Avatar asked Jul 13 '16 12:07

krlbsk


People also ask

How do I index an array in Swift?

To get the first index of an item in an array in Swift, use the array. firstIndex(where:) method. print(i1!)

How do you replace an array in Swift?

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.

What is .first in Swift?

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.

What is element in array Swift?

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 …).


1 Answers

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 
like image 109
Tim Vermeulen Avatar answered Oct 17 '22 00:10

Tim Vermeulen