首页 > 解决方案 > sort an array by comparing a string value swift

问题描述

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?

标签: iosswift

解决方案


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.


推荐阅读