NSSortDescriptor evaluating ascending numbers (Swift)

前端 未结 3 1146
面向向阳花
面向向阳花 2021-01-18 01:00

App has contentid coming in as a number string from a json file:

let contentid: AnyObject! = jsonFeed[\"contentid\"]

let stream:Dictionary = [
         


        
相关标签:
3条回答
  • 2021-01-18 01:13

    In my case I tried it with

    let descriptor: NSSortDescriptor = NSSortDescriptor(key: "formId", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:))) Its working for me.

    0 讨论(0)
  • 2021-01-18 01:21

    The values you want to sort are actually strings and not numbers, thus the strange sort order. For Swift there exist an initializer init(key:ascending:selector:) of NSSortDescriptorand thus you can use selector: "localizedStandardCompare:" as described for example at nshipster.com/nssortdescriptor

    The localizedStandardCompare: gives you a Finder like sorting of string values in a way that numbers are sorted naturally as you would sort numbers. So 1,...,9,10,...,99, 100 etc.

    0 讨论(0)
  • 2021-01-18 01:27
            let descriptor: NSSortDescriptor = NSSortDescriptor(key: "message_time", ascending: true)
            let sortedResults = arrayForMessages.sortedArray(using: [descriptor])
            print(sortedResults)
    
    0 讨论(0)
提交回复
热议问题