我有一个名为prodIDArr
的字符串数组,其值如下...
["1","2","3","4","5","6","7","8","9","10"]
但是当我做这样的事情时..
let maxVal = prodIDArr.max()
我得到maxVal
的值为 9 而不是 10。
这其中可能是什么原因...?
这是一个字符串数组,按字典顺序比较:
"1" < "10" < "2" < ... < "9"
例如"10" < "2"
因为初始字符已经 满足"1" < "2"
.(有关血腥细节,请参阅示例 Swift 中的字符串和字符比较不区分区域设置是什么意思?
使用整数数组将是最佳解决方案:
let prodIDArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let maxId = prodIDArr.max()
print(maxId) // Optional(10)
如果无法做到这一点,则可以强制执行数字比较
let prodIDArr = ["1","2","3","4","5","6","7","8","9","10"]
let maxId = prodIDArr.max(by: { $0.compare($1, options: .numeric) == .orderedAscending })
print(maxId) // Optional("10")
您还可以将原始字符串数组映射到 int 数组
let prodIDArr = ["1","2","3","4","5","6","7","8","9","10"]
let prodNumArray = prodIDArr.map { input in Int(input)!} // or { Int($0)! }
print(prodNumArray.max()!)