0

Say I have a Cat class with this property:

var order: Int?

I have an array of these classes that I need to order by this property:

let sortedCats = cats.sorted(by: { $0.order > $1.order })

I get this error:

"Binary operator '>' cannot be applied to two 'Int?' operands"

What's the proper way to do this?

1
  • 1
    It depends on how you want to treat the orderless cats (those whose order == nil). Should an orderless cat compare less than or greater than any ordered cat? Commented Aug 17, 2020 at 21:21

1 Answer 1

1

Use a default value of .min which is the smallest number you can have on an Int

let sortedCats = cats.sorted(by: { $0.order ?? .min > $1.order ?? .min })

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

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.