Swift whit Xcode uses bubble sorting, custom Array <Any> array sorting method, and returns the sorted array
1. Design Idea:
1. Define a method that accepts a variable array parameter and variable method declaration identified by inout (the role of variable methods: comparison of parameter values)
Method parameter description:
1-1. The array parameter should be set as a variable parameter with inout mark before the type, so that the index value of the array parameter can be transposed, otherwise the parameter in Swift is immutable and only one can be defined in the method body The new variable assigns the data parameters to the newly defined variable;
1-2. The function of the variable method sortClosure, used to judge the size comparison of the specified index value of the array, if it returns true, the array will not be transposed or transposed
Parameter description of sortClosure method:
1-2-1. Accept two object values of any type, used for passing parameters of mySortedArray method index position object, and return Bool value
2. Return type: sorted array
Second, the implementation code
func mySortedArray(数组 array:inout Array<Any>,sortClosue:(Any,Any)->Bool )->Array<Any> { for i in 0 ..< array.count { // If there is only one diagonal in the array, jump out of the loop if 0==array.count-1 { break } // The for loop in Swift does not need to consider the i and j variables nil or out of bounds, Swift will automatically handle for j in i+1 ..< array.count { if sortClosue(array[i],array[j]){} // If the contrast value is false, exchange the position of the specified value Val of the data index else{ array.swapAt(i, j) } } } return array }
3. Scene test
1. Int array test
var list: Array<Any>=[3,5,2,1,4,2,53,2,4,787,5,4,3] list=mySortedArray(数组: &list, sortClosue: {(minVal:Any,maxVal:Any) in return maxVal as! Int > minVal as! Int}) print(list)
2. Object array test
class Student{ var name: String // Name var achievment: UInt // Results init(name:String,achievment:UInt) { self.name=name self.achievment=achievment } } var stuArr:Array<Any> = [Student.init(name: "明月", achievment: 98),Student.init(name: "赵六", achievment: 89),Student.init(name: "落花", achievment: 96),Student.init(name: "阿良", achievment: 90),Student.init(name: "张三", achievment: 78)] stuArr=mySortedArray(数组: &stuArr, sortClosue: {($0 as! Student).achievment > ($1 as! Student).achievment}) for student in stuArr { print((student as! Student).name,(student as! Student).achievment) }