Given an array defined as follow
let list: [Any]
I want to sort it WHEN
- all the values inside it have the same type
Element
- AND
Element
isComparable
.
When it should return the sorted array
So I would need a function that when the array is populated in a way like the followings
let list: [Any] = [10, 11, 0, 2, -1]
let list: [Any] = ["Red", "Green", "Blue"]
let list: [Any] = [true, false, true, true]
does return the sorted array.
When it should return nil
On the other hand when list
contains one of the following examples
let list: [Any] = [CGPointZero, CGPoint(x:1, y:1)] // CGPoint is not comparable
let list: [Any] = [10, "Hello"] // Values of different types
I want nil
as return value.
Any idea?
For the moment, I wrote a little extension to check if all the elements are of the same type (I will be working on this to check if can get a result):
Example:
If your use case allows you to provide a hint to the compiler, you could specify a filter on the type of output that you want:
If the input array does not contain any elements of the specified type then it will just return an empty array. If the type is not a Comparable, then the code won't event compile.
Example:
Compile time solution
Runtime solutions:
UPDATE
Here is non final state. The problem is with casting to comparable. IMHO it is not possible. Until now I didn't know about trick with optional type. Anyway even casting of meta type is not possible because type is not known until runtime. My weak workaround is to list supported comparable types:
UPDATE 2
The second option is to have comparable protocol defined differently (
AnyComparable
). Unfortunately it means to create extensions for all Comparable types. Otherwise there's no way, at compile-time, the compiler can find the correct function/operator (as it doesn't know the types ahead of time).So you have two options:
IMHO there is no other solution