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 replacem
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
This worked for me in Swift 3 without an extension:
struct MyClass: Equatable {
let title: String
public static func ==(lhs: MyClass, rhs: MyClass) -> Bool {
return lhs.title == rhs.title
}
}
Didn't work for me in Swift 3 XCode 8 until I gave my class an extension.
For example:
class MyClass {
var key: String?
}
extension MyClass: Equatable {
static func == (lhs: MyClass, rhs: MyClass) -> Bool {
return MyClass.key == MyClass.key
}
}