我一直在嘗試在swift中使用sortInPlace函數,但它不工作。當我使用排序功能而不是排序時,它可以工作。在swift 2中排序和sortInPlace之間的區別?
請解釋一下這兩個函數之間的區別。如果您可以提供演示使用這兩種功能的小代碼示例,這將非常有幫助。
我一直在嘗試在swift中使用sortInPlace函數,但它不工作。當我使用排序功能而不是排序時,它可以工作。在swift 2中排序和sortInPlace之間的區別?
請解釋一下這兩個函數之間的區別。如果您可以提供演示使用這兩種功能的小代碼示例,這將非常有幫助。
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
FWIW,在Swift 3中沒有sortInPlace
。相反,有一個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]
如果你想使用sortInPlace
或sort
這是變異的功能則數組必須是var
,否則你可能會得到一個誤導錯誤說:
「排序()」有已重新命名爲'sorted()'
'sort' _returns_包含'self'元素的排序數組,其中包含'self'元素保持完好,而'sortInPlace'只是排序'self'。 – courteouselk
你可以很容易地找到自己:CMD - 分別點擊符號並閱讀說明 – vadian
在Swift 3中沒有'sortInPlace'。相反,有一個「排序」和「排序」。在 – Honey