【问题标题】:Sort string array containing Å, Ä and Ö - Swift对包含 Å、Ä 和 Ö 的字符串数组进行排序 - Swift
【发布时间】:2016-12-07 19:19:21
【问题描述】:

我正在尝试按字母顺序对字符串数组进行排序。当字符串不包含 Å、Ä 或 Ö(瑞典语)时,它可以使用标准排序功能。

我想像 A...Z、Å、Ä、Ö 一样订购它。相反,产生的顺序是 A...Z、Ä、Å、Ö。

我尝试使用localizedCompare,但没有成功。在这种情况下,Å 和 Ä 被翻译为“A”,Ö 被翻译为“O”。

let songs = self.allSongs.sort { return $0.title.localizedCompare($1.title) == .OrderedAscending }

关于如何做到这一点的任何想法?

【问题讨论】:

    标签: ios swift string sorting


    【解决方案1】:

    我想像 A...Z、Å、Ä、Ö 一样订购它

    这是瑞典语言环境中定义的顺序,因此您必须 如果当前语言环境不是瑞典语,则明确设置:

    let titles = [ "Z", "Ö", "Å", "Ä", "A"  ]
    
    let swedish = NSLocale(localeIdentifier: "sv")
    let sortedTitles = titles.sort {
        $0.compare($1, locale: swedish) == .OrderedAscending
    }
    
    print(sortedTitles) // ["A", "Z", "Å", "Ä", "Ö"]
    

    对于不区分大小写的排序,添加options: .CaseInsensitiveSearch 论据。

    Swift 3 更新:

    let titles = [ "Z", "Ö", "Å", "Ä", "A"  ]
    
    let swedish = Locale(identifier: "sv")
    let sortedTitles = titles.sorted {
        $0.compare($1, locale: swedish) == .orderedAscending
    }
    
    print(sortedTitles) // ["A", "Z", "Å", "Ä", "Ö"]
    

    【讨论】:

      猜你喜欢
      • 2011-02-10
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      • 2019-05-26
      • 1970-01-01
      • 2020-02-18
      相关资源
      最近更新 更多