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
mutating func customSort(): stackoverflow.com/a/45427102mutating func customSort() { sort { $0.field < $1.field } }