1

I'm trying to sort an array by comparing a string value from two items, the values of the property are a number but of type String. How can I convert them to Int and check which is greater. Current code looks like this.

libraryAlbumTracks = tracks.sorted {
            $0.position!.compare($1.position!) == .orderedAscending
        }

but values like "13" come before "2" because it's a string. I tried to cast the values to Int but because they are optional, I get the error that operand ">" cannot be applied to type Int? Please how can I go around this in the sorted function?

0

2 Answers 2

4

Provide the numeric option when using compare. This will properly sort strings containing numbers and it also works if some of the string don't actually have numbers or the strings have a combination of numbers and non-numbers.

libraryAlbumTracks = tracks.sorted {
    $0.position!.compare($1.position!, options: [ .numeric ]) == .orderedAscending
}

This avoids the need to convert the strings to Int.

Note: You should also avoid force-unwrapping position. Either don't make them optional if it's safe to force-unwrap them, or safely unwrap then or use ?? to provide an appropriate default when comparing them.

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

Comments

1
libraryAlbumTracks = tracks.sorted {
    guard let leftPosition = $0.position, 
          let leftInt = Int(leftPosition),
          let rightPosition = $1.position,
          let rightInt = Int(rightPosition) else { 
        return false 
    }
    return leftInt > rightInt
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.