在swift中自定义排序字符串数组

时间:2015-09-23 03:11:18

标签: arrays string sorting swift2

希望按顺序对数组var myArray = ["Cat","Zoo","Ball","Cat"]进行排序,使所有“Cat”(可以是任何东西)都是数组的@前端,而数组的其余部分按字母顺序排序。

Input Array : ["Cat","Zoo","Ball","Cat"]
Expected Output Array: ["Cat", "Cat", "Ball", "Zoo"]

1 个答案:

答案 0 :(得分:0)

以下代码是我找到的解决方案之一:

var myArray = ["Cat","Zoo","Ball","Cat"]
let OrderString = "Cat"
myArray.sortInPlace({ (s1, s2) in
    //Sorting based on OrderString
    //First string is same as OrderString -- Don't swap order
    if s1 == OrderString{
        return true
    }else if s2 == OrderString { //Second String is same as OrderString -- Swap order
        return false
    }
    return s1.localizedStandardCompare(s2) == NSComparisonResult.OrderedAscending
})

print(myArray)

Demo Link