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

后端 未结 3 951
小蘑菇
小蘑菇 2021-02-01 03:20

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

3条回答
  •  天命终不由人
    2021-02-01 04:03

    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
    

提交回复
热议问题