iosarraysswiftsortingpfobject

"Sorted(by: )" not returning an Array / how to sort an Array of PFObjects in swift


so I can't seem to sort using swifts built in sort function.

I have an Array of PFObjects, if you don't know what those are for the scope of this question it's probably better to imagine it as an array of hashTables.

I'm trying to sort the array using this

self.courseArray = self.courseArray.sorted(by: sortClasses)

and sortClasses looks like:

    func sortClasses(_ x: Any, _ y:Any) ->Bool{
    return ((x as! PFObject).object(forKey: "priority") as! Int) < ((y as! PFObject).object(forKey:"priority") as! Int)
}

Where the key priority will give an Int.

However, when I do this I get this error

Cannot assign value of type '[NSFastEnumerationIterator.Element]' to type 'NSMutableArray'

any suggestions?


Solution

  • Just use native Swift Array rather than NSMutableArray.

    Declare courseArray as

    [PFObject]() 
    

    and use key subscription

    func sortClasses(_ x: Any, _ y:Any) -> Bool {
        return (x as! PFObject)["priority"] as! Int < (y as! PFObject)["priority"] as! Int
    }
    

    You might change other API related to NSMutableArray to the native counterparts.