2015-11-07 64 views
5

我一直在嘗試在swift中使用sortInPlace函數,但它不工作。當我使用排序功能而不是排序時,它可以工作。在swift 2中排序和sortInPlace之間的區別?

請解釋一下這兩個函數之間的區別。如果您可以提供演示使用這兩種功能的小代碼示例,這將非常有幫助。

+3

'sort' _returns_包含'self'元素的排序數組,其中包含'self'元素保持完好,而'sortInPlace'只是排序'self'。 – courteouselk

+3

你可以很容易地找到自己:CMD - 分別點擊符號並閱讀說明 – vadian

+0

在Swift 3中沒有'sortInPlace'。相反,有一個「排序」和「排序」。在 – Honey

回答

14
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 
1

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] 

如果你想使用sortInPlacesort這是變異的功能則數組必須是var,否則你可能會得到一個誤導錯誤說:

「排序()」有已重新命名爲'sorted()'

+1

下面看到我的回答問題是特別標記爲「swift2」,我不確定我們必須發佈有關特定版本的特定問題的語法更新... – Moritz

+1

@EricAya True。我同意但是有人可能不知道'sortInPlace'特定於Swift 2.我正在四處尋找'sortInPlace'並意識到Swift 3中沒有這樣的事情。 – Honey

+1

當然。 :)好吧,我猜這個答案並沒有害處。這只是我正在修理題外話,我不確定這個。 :p – Moritz