我正在尝试对自定义对象的数组进行排序,但出现以下错误:
实例方法“ localizedCaseInsensitiveCompare”要求 '串?'符合“ StringProtocol”
filteredCountriesAndCities?.sorted(by: {$0.countryName?.localizedCaseInsensitiveCompare($1.countryName) == ComparisonResult.orderedAscending})
答案 0 :(得分:2)
您需要处理countryName
为nil的情况,这是最后对nil值进行排序的示例
let sorted = array.sorted {
guard let first = $0.countryName else {
return false
}
guard let second = $1.countryName else {
return true
}
return first.localizedCaseInsensitiveCompare(second) == ComparisonResult.orderedAscending
}