【问题标题】:Difference between sort and sortInPlace in swift 2?swift 2中sort和sortInPlace之间的区别?
【发布时间】:2017-03-29 09:25:53
【问题描述】:

我一直在尝试快速使用 sortInPlace 函数,但它不起作用。当我使用 sort 函数而不是 sortinplace 时,它​​可以工作。

请解释这两个功能之间的区别。如果您能提供小代码示例来演示这两个函数的使用,那将非常有帮助。

【问题讨论】:

  • sort 返回一个包含self元素的排序数组,保持self不变,而sortInPlace只是排序self
  • 您可以自己轻松找到:CMD-点击符号分别阅读说明
  • 在 Swift 3 中没有sortInPlace。取而代之的是sort & sorted。请参阅下面的答案

标签: swift swift2


【解决方案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,在 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,否则你会得到一个误导错误:

    'sort()' 已重命名为'sorted()'

    【讨论】:

    • 该问题被专门标记为“swift2”,我不确定我们是否必须针对特定版本的此类特定问题发布语法更新...
    • @EricAya 真的。我同意 但是人们可能不知道 sortInPlace 是 Swift 2 特有的。我四处寻找什么是 sortInPlace 并意识到在 Swift 3 中没有这样的东西。
    • 当然。 :) 好吧,我猜有这个答案并没有什么坏处。只是我正在修复离题的​​东西,我不确定这个。 :p
    猜你喜欢
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多