swift - 在 Swift 中比较两个对象

标签 swift

如何比较两个通用对象。下面是进行比较的示例代码,这一行 elem > value 抛出一个错误,提示 Could not find overload for '>' that accepts the supplied arguments

func index<T : Equatable>(array: T[], value: T) -> Int {
    for (index, elem) in enumerate(array) {
        if elem > value {
            return index
        }
    }
    return array.count
}

最佳答案

来自 Swift 引用:

The Equatable protocol makes it possible to determine whether two values of the same type are considered to be equal.

There is one required operator overload defined in the protocol: ==.

不保证Equatable对象必须实现 >运算符,它解释了您的错误。

看看 Comparable 然而。注意 comparable 只需要重载 <==运营商。

但是,如果不是a < b也不是 a == b ,你可以假设 a > b .

关于swift - 在 Swift 中比较两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24093081/

相关文章:

swift - 将前导零添加到将与文本一起打印在字符串中的数字

ios - 如何处理 iOS 应用程序中的“返回 Safari”按钮单击

ios - MapBox 在 CGRect 中获取 visibleCoordinateBounds

swift - addPersistentStoreWithType 到底在做什么?

ios - 尝试使用 CALayers 制作水龙头滴水的动画

ios - 添加每个 UITableViewCell 单元格中每次出现的键

swift - 协议(protocol)未被执行

ios - Swift - UIViews 以编程方式排序

ios - 转换 [字符串 : AnyObject] to [String: Any]

ios - 带有自定义 UICollectionViewLayout 的 UICollectionViewCell 仅在一个 subview 上创建视差动画