【问题标题】:Swift Array Sort by Property Error : Instance method 'localizedCaseInsensitiveCompare' requires that 'String?' conform to 'StringProtocol'Swift 数组按属性错误排序:实例方法“localizedCaseInsensitiveCompare”需要“字符串?”符合'StringProtocol'
【发布时间】:2020-12-22 01:33:04
【问题描述】:

我正在尝试对这个自定义对象数组进行排序,但出现以下错误:

实例方法“localizedCaseInsensitiveCompare”要求 '细绳?'符合'StringProtocol'

filteredCountriesAndCities?.sorted(by: {$0.countryName?.localizedCaseInsensitiveCompare($1.countryName) == ComparisonResult.orderedAscending})

【问题讨论】:

    标签: arrays swift sorting object


    【解决方案1】:

    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
    }
    

    【讨论】:

    • @TheBear 如果您希望 nil 属性位于集合的开头,您可以简单地执行 $0.countryName?.localizedCaseInsensitiveCompare($1.countryName ?? "") == .orderedAscending
    • 感谢 Leo 的提示
    • 我欠你一只熊!干杯
    猜你喜欢
    • 1970-01-01
    • 2021-06-23
    • 2019-12-13
    • 2021-10-08
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多