Charlie Egan
Charlie Egan

Reputation: 5203

Sort NSArray Swift Error: could not find an overload for 'sort' that accepts the supplied arguments

I'm trying to learn the basics of Swift, currently trying to create a list of random numbers and sorting them.

var myNSArray = [1,2,3,4]
sort(myNSArray,>) //this works  =  [4,3,2,1]

var myArray: NSMutableArray = []
for i in 0..20 {
    myArray.addObject(Int(rand())%100)
}

var myNew: NSArray = myArray.mutableCopy() as NSArray
var mySorted = sort(myNew,>) //This give an error

This is the error:

...error: could not find an overload for 'sort' that accepts the supplied arguments

EDIT: I was able to rewrite this code using Array as follows:

var myArray: Int[] = []
for i in 0..20 {
    myArray.append(Int(rand())%100)
}
myArray = sort(myArray,>)

Which is a lot cleaner!

Upvotes: 2

Views: 1291

Answers (1)

Logan
Logan

Reputation: 53132

In your first example, myNSArray isn't an NSArray:

var myNSArray = [1,2,3,4]
sort(myNSArray,>) //this works  =  [4,3,2,1]

enter image description here

But in these examples:

var myArray: NSMutableArray = []
for i in 0..20 {
    myArray.addObject(Int(rand())%100)
}

var myNew: NSArray = myArray.mutableCopy() as NSArray
var mySorted = sort(myNew,>) //This give an error

It is an NSArray and an NSMutableArray explicitly. These classes don't declare sort()

Upvotes: 4

Related Questions