Difference between sort and sortInPlace in swift 2?

寵の児 提交于 2019-12-19 18:54:51

问题


I have been trying to use the sortInPlace function in swift but it is not working. When I use the sort function instead of sortinplace it works.

Please explain the difference between these 2 function. It would be very helpful if you can provide small code sample demonstrating the use of both functions.


回答1:


var mutableArray = [19, 7, 8, 45, 34]

// function sort sorts the array but does not change it. Also it has return

mutableArray.sort()

mutableArray
// prints 19, 7, 8, 45, 34

// function sortInPlace will mutate the array. Do not have return

mutableArray.sortInPlace()

mutableArray
// prints 7, 8, 19, 34, 45



回答2:


FWIW, in Swift 3 there is no sortInPlace. instead there is a sort & sorted.

var mutableArray = [19, 7, 8, 45, 34]

mutableArray.sortInPlace() // error : 'sortInPlace()' has been renamed to 'sort()'

mutableArray.sort() // 
print(mutableArray) // [7, 8, 19, 34, 45]

mutableArray.sorted()

print(mutableArray) // [19, 7, 8, 45, 34]
let anotherArray = mutableArray.sorted()

print(anotherArray) // [7, 8, 19, 34, 45]

If you want to use sortInPlace or sort which are mutating functions then the array must be a var, otherwise you could get a misleading error saying:

'sort()' has been renamed to 'sorted()'



来源:https://stackoverflow.com/questions/33580177/difference-between-sort-and-sortinplace-in-swift-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!