Given an array defined as follow
let list: [Any]
I want to sort it WHEN
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:
extension _ArrayType where Generator.Element == Any {
func filterByType() -> [T] {
var output = [T]()
for i in self {
if let j = i as? T {
output.append(j)
}
}
return output
}
}
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:
let list: [Any] = [10, "Hello", 3, false, "Foo", "Bar", 1] // Values of different types
var output = list.filterByType() as [Int]
output.sortInPlace()