我有一个 Source 对象数组:
class Source: NSObject {
var sourceName: String
var country: String
}
我想按我从 NSLocale 获得的国家名称对该数组进行排序。
if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
print(countryCode)
}
如何先使用当前位置对象等国家名称对对象进行排序,然后再排序。
谢谢
最佳答案
您可以做的是首先像通常按国家/地区名称一样对数组进行排序:
array.sort{ $0.sourceName < $1.sourceName }
然后从数组中删除当前国家并将其添加为第一个元素:
if let index = array.index(where: { $0.sourceName == "currentCountry" }) {
let source = array.remove(at: index)
array.insert(source, at: 0)
}
我可能没有使用你想要的正确变量,我不确定 Source
变量是什么意思。
此外,确保 "currentCountry"
字符串是您从您的方法中正确获得的内容。
关于ios - 使用当前位置值对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47589990/