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?

You've hit a problem with Swift's generics that can't be solved the way you like it right now (maybe in a future Swift version). See also Swift Generics issue.

Currently, you'll need to define a function (for example at the global scope):

```
func isSorted<T: Comparable>(array: Array<T>) -> Bool {
for i in 1..<array.count {
if array[i-1] > array[i] {
return false
}
}
return true
}
let i = [1, 2, 3]
let j = [2, 1, 3]
let k = [UIView(), UIView()]
println(isSorted(i)) // Prints "true"
println(isSorted(j)) // Prints "false"
println(isSorted(k)) // Error: Missing argument for parameter #2 in call
```

The error message is misleading, IMHO, as the actual error is something like "UIView doesn't satisfy the type constraint Comparable".

The alternative solution to a free function is to do what Swift's built-in `Array.sort`

and `Array.sorted`

methods do, and require that you pass a suitable comparator to the method:

```
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
```

In Swift 2.0 you can now extend protocols!

```
extension CollectionType where Generator.Element: Comparable {
var isSorted: Bool {
...
}
}
[1, 2, 3, 4].isSorted // true
["a", "b", "c", "e"].isSorted // true
[/* Anything not implementing `Comparable` */].isSorted // <~~ Type-error
```

Similar Questions

Help me with Optional hell in Swift. How to return count of array for key R. self.jsonObj can be null func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return (

I have an assignment for school where the user has to input numbers and the program has to determine whether they are sorted or not. If anyone can help with my code that would be awesome. I am having

I have an array of Sorted integers. We can use binary search to find an element . Now if one element of sorted array is interchanged with another element. What would be the best way to find the interc

[This is an interview question. I couldn't find a duplicate.] An array contains two sub- sorted arrays. Give an inplace algorithm to sort two sub arrays. for ex: I/P: 1 4 5 7 8 9 2 3 6 10 11 O/P: 1 2

I have an array of myObjects called arrayToFilter. One (element?) of myObject is an array of bezierpaths. I am comparing the bezierpath at a particular index (thispath) to a second path, and making fi

I am writing an easy program the just returns true if an array is sorted else false and I keep getting an exception in eclipse and I just can't figure out why. I was wondering if someone could take a

I have a sorted array ( in ascending order) and I want to find the subscript of a number in the array which is the the next highest number to a given number. For example,if I have 67 as a given number

Given a sorted but rotated array how do you find the pivot ? I was asked this question in an interview. What is a rotated array ? I got this on internet but its not clear at all. In a rotated sorted

Im wondering how to essentially transform the objective c code below into swift. This will loop through all the subviews on my desired view, check if they are textfields, and then check if they are e

Is there a pythonic way to check if a list is already sorted in AESC or DESC. listtimestamps=[1,2,3,5,6,7] something like listtimestamps.isSorted() that returns True or False. EDIT: I want to input a

In CoreData I have defined an ordered to-many relationship. This relationship is defined in Swift like this: @NSManaged var types : NSMutableArray However, to use Swift at it's best, I want to use a

This question already has an answer here: Swift - Read plist 7 answers Has anyone figured out how to read a plist into an array or dictionary in Swift? I cannot seem to figure it out. I am used

Given 3 sorted array. Find 3 elements, one from each array such that a+b=c. Can it be done less than O(n^3) time complexity? Please help me.

I'm trying to add an extension method in Array like so: extension Array { func contains(obj: T) -> Bool { let filtered = self.filter {$0 == obj} return filtered.count > 0 } } But self.filter {$

Let me start by saying this a homework question that I am having trouble with. I have sorted an array and what I need to do is use another array to remove duplicates by iterating over the first and co

after submited form i want to check array if array is empty alert error for user. but i get error when submited form: PHP $errors = array_filter($_POST['session']); if (!empty($errors)) { foreach ($_

Question Is it possible to invoke countElements() with an Array in my setup? Problem in detail The countElements() works fine with String. However I cannot figure out how to cast thing to an Array and

This question already has an answer here: Swift how to sort array of custom objects by property value 3 answers I have an Array called myArray. In this array I have several objects from a cus

Assume we have an array of optionals defined: var arrayOfOptionals: [String?] = [Seems, like, an, nil, of, optionals] I can force unwrap it in a short way: var arrayForCrash = arrayOfOption

I've been tasked with creating a method that will print all the indices where value x is found in a sorted array. I understand that if we just scanned through the array from 0 to N (length of array)

What is the time complexity to remove the smallest value from an array with n elements that is sorted from smallest to largest? I believe it is O(1) because the smallest value is the first value of th

Let's say I have an Array ary = [0.0, 1.0, 5.0, 1.0, -2.0, 3.5], and I want as output another array of the same size containing ary's indices in sorted-by-value-order. In other words, the output shoul

I am new to swift I am trying to append items to infopacks array but somehow no item is added to the array import UIKit class Tag: NSObject { var id:Int? var infopacks = [InfoPack]() init(tag :AnyObje

Problem: Given a sorted array of integers find the most frequently occurring integer. If there are multiple integers that satisfy this condition, return any one of them. My basic solution: Scan throu

Swift's filter method is defined as follows: func filter(includeElement: (T) -> Bool) -> [T] Why does filter definition in Swift's array does not have <T> in its definition (i.e. filter(.

I was asked this question recently in an interview : What is the most efficient way to find a repeated number in a sorted array? My answer was based on using a hash table with key as array element and

I'm trying to build an extension that adds some of the convenience functionality of NSArray/NSMutableArray to the Swift Array class, and I'm trying to add this function: func indexOfObject(object:AnyO

I'm wondering whether somebody can help me with this problem. I'm using C/C++ to program and I need to do the following: I am given a sorted array P (biggest first) containing floats. It usually has a

I have an array, $items, which contains lot of informations: name, size, quantity, color, id... I'm using 'for' loops to sort $items values by color and save the sorted values in a new array, But the

In Swift, is there any way to check if an index exists in an array without a fatal error being thrown? I was hoping I could do something like this: let arr: [String] = [foo, bar] let str: String?

I'm trying to make a variation on Array for a very specific purpose. When I have the following: public class TileArray extends Array { // Intentionally empty - I get the error regardless } Why can't

I made these (marked with red border) IBOutlets using ctrl + drag But i don't like to have the exact same line 9 times (DRY) How do i put these IBOutlets in an Array?

In Swift, I'm trying to build a large collection of items. When creating elements in CoreData on-the-go, this is very speedy. However when trying to keep an index to those items, creating an array Swi

How can i check if a number is decimal or not using swift? With Objective-C: if (number == (int) number) { //decimal } else { //not decimal }

I apologize if this has been asked here - I've hunted around here and in the Tentative NumPy Tutorial for an answer. I have 2 numpy arrays. The first array is similar to: 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0

How to check if array like this array(3) { [0]=> array(0) { } [1]=> array(0) { } [2]=> array(0) { } } is actually empty ? Because for me this is an empty array but for the empty() this is an

Continuing to play around in Swift and trying to convert something from the C world and have been stuck trying various syntax. I have some fixed data I want to initialize into a structure array. Here'

Given an 2-D Array of n*n elements: all rows are sorted all columns are sorted For example: 1 5 7 2 6 8 3 9 10 convert it to a 1-D sorted array. Is there a solution better than O(nlog(n)).

Given a dictionary I need to check to see if the value is Dictionary, Array, or Other. I get the following error: Downcast pattern value of type Dictionary cannot be used // Type of dictionary to enum

I am trying to figure out whether a variable is part of an array. This is the code: let Name = Tim var i = let Friends = [Jim, Tim, Anna, Emma] if Name in Friends { i = Is a Friend }

I am sorting an NSMutableArray on my field date but it does not take into account the time. If the date is the same, the time is still sorted random. What am I doing wrong? The field date is of th

Hi I have an array of distances a= np.array([20.5 ,5.3 ,60.7 ,3.0 ], 'double') and I need the indices of the sorted array (for example [3, 1, 0, 2], for a.sort()). There is a function in numpy to do t

I have an array that may look like this... var array = array(1,4,7,8,12,15); The values in the array will always be integers, and always will go up, or could be the same as the previous, but at least

What is the complixety of turning a sorted array of size n to a legal 2-4 B tree? What would it be if the array wasn't sorted. I believe that the first answer should be O(logn) (As many splits that we

I am new to programming. I am making a little database program for iOS in swift. I have a person class: class Person : NSObject { var firstName : String var lastName : String init (firstName : String

Given an array of integers, I would like to find the minimum number x such that increasing or decreasing the elements in the array by a number in the range of 0 to x will result in an array sorted in

This question already has an answer here: How do I sort a Set to a List in Java? 8 answers HashMultimap return a set of values for a given key.how do i convert this java set to a sorted array?

we got an increasing sorted multidimensional array for example: int[][] mat = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}}; How can I use binary search to find a specific number? let's say im

I have 10 input or more and need to check for this array do not duplicate. if duplicate entry from user will be show that error to user too. sample Check array qty[] if dup. will be show and can not e

I'm trying to add an enum type to an Array and am getting an error. I am able to add a String and other types, but this enum is failing. Does anyone know what might be going wrong here? enum Domain {