1

I would like to create a Swift 4 extension on a Swift Array. The function should sort the array in-place.

The compiler complains seems to assume that arrays are immutable, as it complains on the function I created. I'd like to solve this, but do not know how. Please do note that the requirement is to sort the array in-place (with sort) and not creating a new array (like one would do with sorted).

struct MyStruct {
    var field: String
}

typealias MyStructList = [MyStruct]

// requirement: extend MyStructList with custom sort

extension Array where Element == MyStruct {
    func customSort() -> [MyStruct] {
        return sort { $0.field < $1.field } 
    }   
}

Compiler complains: Cannot use mutating member on immutable value: 'self' is immutable

2
  • mutating func customSort(): stackoverflow.com/a/45427102 Commented May 7, 2018 at 11:19
  • 2
    and don't return anything mutating func customSort() { sort { $0.field < $1.field } } Commented May 7, 2018 at 11:20

3 Answers 3

7

You want to be calling sorted(by:), which returns a new, sorted Array instance rather than sort(by:), which does sorting in place and hence mutates the Array.

extension Array where Element == MyStruct {
    func customSort() -> [MyStruct] {
        return sorted(by: {$0.field < $1.field})
    }
}

If you actually want to sort the Array in place, you have to mark your customSort function as mutating and change the function signature to return Void, since there's no new Array created.

extension Array where Element == MyStruct {
    mutating func customSort() {
        sort(by: {$0.field < $1.field})
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Two issues:

  1. You have to mark the function as mutating
  2. If you want to sort in place there is no return value

    extension Array where Element == MyStruct {
        mutating func customSort() {
            sort { $0.field < $1.field }
        }
    }
    

And please name methods / functions camelCased.

Comments

1

sort is a mutable function that sorts an Array in-place. sorted(by:) is the function you are looking for. Rename sort to sorted.

If you are looking to sort the Array in-place, then rewrite your function declaration to include the mutating qualifier.

So the following:

func custom_sort()

becomes:

mutating func custom_sort()

The mutating function sort(by:) does not return anything, therefore your return is erroneous. Remove -> [MyStruct] as well.

1 Comment

Thanks for your answer and rightly pointing out the CamelCase (I edited the question).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.