How do I do indexOfObject or a proper containsObject

后端 未结 8 974
说谎
说谎 2020-12-03 03:00

With an array: How do I do indexOfObject or a proper containsObject?

I mean I know I could just bridge the Array to NSArray an

8条回答
  •  忘掉有多难
    2020-12-03 03:51

    Apple provide an example of exactly this in the The Swift Programming Language book. Specifically, see the section on Type Constraints in Action (p621 in the iBook).

    func findIndex(array: [T], valueToFind: T) -> Int? {
        for (index, value) in enumerate(array) {
            if value == valueToFind {
                return index
            }
        }
        return nil
    }
    

    Everything depends upon your type implementing Equatable.

    The Swift Programming Language covers that and explains how to implement that protocol:

    “The Swift standard library defines a protocol called Equatable, which requires any conforming type to implement the equal to operator (==) and the not equal to operator (!=) to compare any two values of that type. ”

    NSHipster has a couple of relevant posts on this subject:

    Swift Default Protocol Implementations Swift Comparison Protocols

    I also found this answer very useful in implementing Equatable:

    How do I implement Swift's Comparable protocol?

    Alhough it mentions Comparable, Equatable is a subset and the explanation is good.

    Excerpts above from: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/gb/jEUH0.l

提交回复
热议问题