我想扩展Array类,这样它就可以知道它是否排序(升序)。我想添加一个名为isSorted的计算属性。我如何声明数组的元素是可比较的?
我目前在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出现 Could not find an overload for '>' that accepts the supplied arguments错误
当然,我仍然收到一个错误,因为Swift不知道如何比较元素。如何在Swift中实现此扩展?还是我做错了什么?
发布于 2016-09-09 18:49:30
对我来说,最灵活的解决方案是NSAddict和Wes Campaigne的答案的组合。即结合了能够扩展协议和将比较器函数作为自变量传递的优点。这消除了仅将其与数组一起使用以及将其约束为符合Comparable协议的元素的限制。
extension CollectionType
{
func isSorted(isOrderedBefore: (Generator.Element, Generator.Element) -> Bool) -> Bool
{
var previousIndex = startIndex
var currentIndex = startIndex.successor()
while currentIndex != endIndex
{
if isOrderedBefore(self[previousIndex], self[currentIndex]) == false
{
return false
}
previousIndex = currentIndex
currentIndex = currentIndex.successor()
}
return true
}
}这可以在任何Collection类型上使用,并且可以根据需要定义排序标准。
https://stackoverflow.com/questions/24602595
复制相似问题