Sorting the [Any] array

后端 未结 3 576
栀梦
栀梦 2020-12-28 08:41

Given an array defined as follow

let list: [Any]

I want to sort it WHEN

  1. all the values inside it have the sa
3条回答
  •  清酒与你
    2020-12-28 09:22

    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()
    

提交回复
热议问题