Comparing objects in an Array extension causing error in Swift

后端 未结 6 534
遥遥无期
遥遥无期 2021-01-22 15:51

I\'m trying to build an extension that adds some of the convenience functionality of NSArray/NSMutableArray to the Swift Array class, and I\'m trying to add this function:

6条回答
  •  后悔当初
    2021-01-22 16:35

    Here's a relevant example from Apple's "The Swift Programming Language" in the "Generics" section:

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

    The key idea here is that both value and valueToFind must of a type that is guaranteed to have the == operator implemented/overloaded. The is a generic that allows only objects of a type that are, well, equatable.

    In your case, we would need to ensure that the array itself is composed only of objects that are equatable. The Array is declared as a struct with a generic that does not require it to be equatable, however. I don't know whether it is possible to use extensions to change what kind of types an array can be composed of. I've tried some variations on the syntax and haven't found a way.

提交回复
热议问题