0

I'm using Parse and I have an array of PFObjects called "scorecardData". Each PFObject has a "score" property that is of type Int. I'm trying to sort my array by "score" but I'm getting the following error: "Binary operator '<' cannot be applied to two 'AnyObject?' operands". I'm not sure what I'm doing wrong here. I also tried down casting the objectForKey("score") as! Int but its not letting me do this. Any suggestions? Thanks in advance.

    var scorecardData = [PFObject]()

    scorecardData.sortInPlace({$0.objectForKey("score") < $1.objectForKey("score")})

3 Answers 3

2

You declared scorecardData variable as Array of PFObject. Why are you trying access PFObject property using objectForKey: reserved? Anyway I am not parse expert. But if you declared your array as [PFObject] you can use:

scorecardData.sortInPlace({$0.score < $1.score})

But this won't work unless you subclass PFObject for a more native object-oriented class structure. If you do that remember also to specify:

var scorecardData = [YOUR_NEW_CLASS]()

I strongly recommend subclassing PFObject to make use of all swift type-safe goodies.

But if you want to keep your data structure you can use:

scorecardData.sortInPlace({($0["score"] as! Int) < ($1["score"] as! Int)})

Keep in mind that it's dangerous, and in future avoid it.

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

1 Comment

Thanks zuziaka! Your solution worked. I'm still new at programming and will look into subclassing PFObject for this project to make my code better.
1

If you want to Sort your array of PFOject... You can do this

extension Array where Element:PFObject {
    func sort() -> [PFObject] {
        return sort { (first, second) -> Bool in
            let firstDate   = first.objectForKey("time") as! NSDate//objectForKey(Constants.Parse.Fields.User.fullName) as? String
            let secondDate  = second.objectForKey("time") as! NSDate//objectForKey(Constants.Parse.Fields.User.fullName) as? String
            return firstDate.compare(secondDate) == .OrderedAscending
        }
    }
}

Comments

0

Have you tried doing this?

var query = PFQuery(className:"ScoreCard")

    // Sorts the results in ascending order by the score field
query.orderByDescending("score")

query.findObjectsInBackgroundWithBlock {

Comments

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.