I want to extend Array class so that it can know whether it is sorted (ascending) or not. I want to add a computed property called isSorted. How can I state the elements of the Array to be comparable?
My current implementation in 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
The error Could not find an overload for '>' that accepts the supplied arguments
Of course, I still got an error because Swift doesn't know how to compare the elements. How can I implement this extension in Swift? Or am I doing something wrong here?
Array<Comparable>, but you can implement a function that operates onArray<Comparable>. Have a look at stackoverflow.com/a/24565627/1489997NSArraycan only store objects, and you can ask them whether they implement a protocol or respond to a selector (compare:). Also, you can force casting in Objective-C. With Swift, the problem is harder as Swift doesn't allow you to "work around" the compiler. Also, there are@objcprotocols and non-@objcprotocols and you can only check whether a type conforms to the later, butComparableis non-@objc. That's whylet foo = (bar as Any) as? Comparabledoesn't work: the compiler does not allow you to "trick" it.