Difference between sort and sortInPlace in swift 2?

前端 未结 2 1555
有刺的猬
有刺的猬 2021-01-18 11:48

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 d

2条回答
  •  礼貌的吻别
    2021-01-18 12:00

    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()'

提交回复
热议问题