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

后端 未结 3 899
小蘑菇
小蘑菇 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
    
    0 讨论(0)
  • 2021-02-01 04:06

    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
        }
    }
    
    0 讨论(0)
  • 2021-02-01 04:09

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题