我想扩展Array类,以便它可以知道它是否已经排序(升序).我想添加一个名为的计算属性isSorted.如何声明Array的元素可以比较?
我目前在Playground中的实现
extension Array {
var isSorted: Bool {
for i in 1..self.count {
if self[i-1] > self[i] { return false }
}
return true
}
}
// The way I want to get the computed property
[1, 1, 2, 3, 4, 5, 6, 7, 8].isSorted //= true
[2, 1, 3, 8, 5, 6, 7, 4, 8].isSorted //= false
Run Code Online (Sandbox Code Playgroud)
错误 Could not find an overload for '>' that accepts the supplied arguments
当然,我仍然有一个错误,因为Swift不知道如何比较元素.如何在Swift中实现此扩展?或者我在这里做错了什么?