0

I have to sort an array of object using one parameter. I have created an entity, below is my JSON :

{
"Name": "Amit",
"Progress": "38",
"Color": "red",
},
  {
"Name": "Sonu",
"Progress": "70",
"Color": "green",
}

Below is my entity class:

class Scoreboard {

    // MARK: - Properties
    var scoreboardName: String? = ""
    var scoreboardProgress: String? = "0"
    var scoreboardColor: String? = ""        
}

This JSON data I have pass into table, The problem is How can I do sorting based on 'Progress'?

I tried below code:

scoreboardArray = scoreboardArray.sorted(by: {($0.scoreboardProgress() < $1.scoreboardProgress())})

But it's not working. Please anyone suggest me.

1
  • 1
    Like Sh_Khan said, remove the optional (?) if you are giving default value to variables. It is redundant. Commented Aug 6, 2018 at 18:25

1 Answer 1

2

Can you try

scoreboardArray = scoreboardArray.sorted {
   Int($0.scoreboardProgress!)! < Int($1.scoreboardProgress!)! 
}

also if you assign a default value , it's better to remove ?

Irrelevant but why not use Decodable

class Scoreboard : Decodable {
Sign up to request clarification or add additional context in comments.

3 Comments

@user2786. be warned that if scoreboardProgress contains a string value that can't be converted into Int, this code will crash
@AwaisFayyaz scoreboardProgress has a default value
Well, scoreboardProgress can be assigned such a string value accidentally or as a result of error. I just try to remain on safe side, in case anything goes wrong.

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.