ios - 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?
解决方案
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.
推荐阅读
- python - Keras/Tensorflow:通道顺序优先和损失函数轴 -1
- android - 更新后修改 SharedPreferences Array
- go - 通过注入类型查找切片元素的模式
- c# - 使用 MVVM 时如何在 WPF 中的窗口之间切换?
- sql-server - SQL Server CASE 表达式未按预期计算
- rally - 通过 Rally REST API 提取用户故事/功能详细信息时如何检索标签列表
- asp.net - 日期倒数计时器(日期从数据库加载)
- javascript - SyntaxError:相邻的 JSX 元素必须包含在封闭标记中
- objective-c - Apple 查找的扩展
- nixops - nixops:在具有现有 nixos 的机器上部署时如何使用本地 ssh 密钥(targetEnv 没有)?