2

I am trying to write an extension where I define a new method for sorting the contained objects in-place by their property using NSSortDescriptorclass. However, I failed to populate the mutable version of self for some reason and getting the following error:

Cannot find an initializer for type NSMutableArray that accepts an argument list of type (array: Array<T>)

Here is my method:

extension Array {

    public mutating func sortInPlace(field: String, ascending: Bool) {

        let mutableArray = NSMutableArray(array: self) // error here.

        let sortDescriptor = NSSortDescriptor(key: field, ascending: ascending)     
        mutableArray.sortUsingDescriptors([sortDescriptor])

        self = mutableArray as AnyObject as! [Generator.Element]
    }
}

I also tried the following but no luck:

let mutableArray = NSMutableArray(array: self as! [AnyObject])
0

1 Answer 1

1

Without seeing your extension definition it's hard to say, but this works for me:

extension Array where T : AnyObject {
    func toMutableArray() -> NSMutableArray {
        return NSMutableArray(array: self)
    }
}

let array: [NSString] = ["A", "B"]
let mArray = array.toMutableArray()

print(mArray) // ( A, B )

The problem here is you need to constrain the extension on Array to only take in an array of AnyObject. String is a struct, not a class (AnyObject is constrained to reference types). This is also why I needed the type specifier of [NSString] on my array. Otherwise, it would be an array of structs, not an array of String values.

Sign up to request clarification or add additional context in comments.

1 Comment

great! I've added a better explanation to my answer.

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.