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

2019-03-09 08:16发布

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.

标签: ios swift3
3条回答
成全新的幸福
2楼-- · 2019-03-09 08:34

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
    }
}
查看更多
Fickle 薄情
3楼-- · 2019-03-09 08:42

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
查看更多
该账号已被封号
4楼-- · 2019-03-09 08:54

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
    }
}
查看更多
登录 后发表回答