我想扩展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中实现此扩展?还是我做错了什么?
发布于 2014-07-16 05:27:35
自由函数的另一种解决方案是执行Swift内置的Array.sort和Array.sorted方法,并要求您将合适的比较器传递给该方法:
extension Array {
func isSorted(isOrderedBefore: (T, T) -> Bool) -> Bool {
for i in 1..<self.count {
if !isOrderedBefore(self[i-1], self[i]) {
return false
}
}
return true
}
}
[1, 5, 3].isSorted(<) // false
[1, 5, 10].isSorted(<) // true
[3.5, 2.1, -5.4].isSorted(>) // true发布于 2015-06-16 00:27:54
在Swift 2.0中,您现在可以扩展协议!
extension CollectionType where Generator.Element: Comparable {
public var isSorted: Bool {
var previousIndex = startIndex
var currentIndex = startIndex.successor()
while currentIndex != endIndex {
if self[previousIndex] > self[currentIndex] {
return false
}
previousIndex = currentIndex
currentIndex = currentIndex.successor()
}
return true
}
}
[1, 2, 3, 4].isSorted // true
["a", "b", "c", "e"].isSorted // true
["b", "a", "c", "e"].isSorted // false
[/* Anything not implementing `Comparable` */].isSorted // <~~ Type-error请注意,因为我们使用Indexable.Index而不是简单的Int作为索引,所以我们必须使用while循环,这看起来不太美观和清晰。
发布于 2019-04-30 02:24:28
在Swift 4.2和更高版本中,您可以通过一些序列切片将allSatisfy和zip拼凑在一起:
extension Array where Element: Comparable {
func isAscending() -> Bool {
return zip(self, self.dropFirst()).allSatisfy(<=)
}
func isDescending() -> Bool {
return zip(self, self.dropFirst()).allSatisfy(>=)
}
}https://stackoverflow.com/questions/24602595
复制相似问题