如何解决Swift数组按属性排序错误:实例方法“ localizedCaseInsensitiveCompare”要求使用“字符串?”符合'StringProtocol'
实例方法“ localizedCaseInsensitiveCompare”要求 '串?'符合“ StringProtocol”
filteredCountriesAndCities?.sorted(by: {$0.countryName?.localizedCaseInsensitiveCompare($1.countryName) == ComparisonResult.orderedAscending})
解决方法
您需要处理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
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。