【问题标题】:Cannot invoke '<' with an argument list of type '(T, T)'无法使用类型为“(T,T)”的参数列表调用“<”
【发布时间】:2015-01-09 20:49:23
【问题描述】:

我尝试实现一个函数,它会在数组中找到最小值的索引:

func minIndex<T: Equatable>(array: [T]) -> Int {
    var minValue = array[0]
    var minIndex = Int()

    for (index, item) in enumerate(array) {
        if item < minValue as T {
            minValue = item
            minIndex = index
        }
    }
    return minIndex
}

但我在行上有一个错误“无法使用类型为 '(T, T)' 的参数列表调用 '

if item < minValue as T {

【问题讨论】:

    标签: swift


    【解决方案1】:

    您需要将元素设为Comparable,以便它们可以与&lt; 进行比较:

    func minIndex<T: Comparable>(array: [T]) -> Int {
        var minValue = array[0]
        var minIndex = Int()
    
        for (index, item) in enumerate(array) {
            if item < minValue {  // Your " as T" cast is not needed here
                minValue = item
                minIndex = index
            }
        }
        return minIndex
    }
    

    Equatable只表示可以和==比较。

    【讨论】:

    • 谢谢!如果我在 Array 扩展中实现它呢?通过此更改: func minIndex() -> Int { var minValue = self[0] ... for (index, item) in enumerate(self) { if item
    • @AlesTsurko:您(当前)无法定义只能应用于受限数组类型的扩展方法(例如,要求元素是 Comparable)。有关类似问题,请参阅 stackoverflow.com/questions/24938948/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    相关资源
    最近更新 更多