Swift错误:二进制运算符'>'无法应用于两个T操作数

Yi *_*ang 0 swift

我正在为数组编写mutaitin函数。我无法比较数组组件,如下所示:

extension Array {
    mutating func mutFunc() {
        while self[1]>self[2]{

        }
     }
}
Run Code Online (Sandbox Code Playgroud)

数组必须是Int类型的数组。我什至无法使用这种方式进行比较。

while Int(self[1])>Int(self[2]){        
}
Run Code Online (Sandbox Code Playgroud)

我的代码有什么问题?

mat*_*att 5

您无法在Swift 1.2或更低版本中执行此操作。这正是whereSwift 2.0 中的扩展子句解决的问题。这样,您可以仅在其元素类型采用Comparable(甚至Int)的范围内仅扩展Array,从而保证>已定义。

extension Array where Element : Comparable {
    // ... your function involving > goes here
}
Run Code Online (Sandbox Code Playgroud)