Sorting the [Any] array

后端 未结 3 579
栀梦
栀梦 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:14

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

    extension _ArrayType where Generator.Element == Any{
    
        func hasEqualTypeAndComparable()->Bool{
    
            if self.count > 0{
                let firstType = self.first?.dynamicType
    
                for val in self{
                    if firstType != val.dynamicType{
                        return false
                    }
                }
    
                return self.first is Comparable
            }
    
            return false
        }
    
    }
    

    Example:

    //Example 1 
    var values:[Any] = [2,1,4,3,"Hola"]
    values.hasEqualTypeAndComparable() // Print false
    
    //Example 2
    var values:[Any] = [2,1,4,3]
    values.hasEqualTypeAndComparable() // Prints true
    

提交回复
热议问题