Swift sort dictionary by value

前端 未结 3 976
眼角桃花
眼角桃花 2020-12-18 12:29

I have a dictionary, [String : Double] with the following data:

Museum1 : 8785.8971799638
Museum2 : 34420.9643422388
Museum3 : 826.467789130732
         


        
相关标签:
3条回答
  • 2020-12-18 13:07

    It is not clear what your expectations are. There is really no such thing as a sorted dictionary. Your code is basically correct except for a misplaced parenthesis. I tried this:

    let d = ["Museum1":8785.8971799638,
    "Museum2":34420.9643422388,
    "Museum3":826.467789130732,
    "Museum4":304120.342151219]
    
    for (k,v) in (Array(d).sorted {$0.1 < $1.1}) {
        println("\(k):\(v)")
    }
    

    Result:

    Museum3:826.467789130732
    Museum1:8785.8971799638
    Museum2:34420.9643422388
    Museum4:304120.342151219
    

    If you think that's wrong, you need to explain why.

    0 讨论(0)
  • 2020-12-18 13:25

    In Swift 2.2, this works

    for (k,v) in (Array(d).sort {$0.1 < $1.1}) {
        print("\(k):\(v)")
    }
    

    Swift 3, it also works:

    for (k,v) in (Array(yourDictionary).sorted {$0.1 < $1.1}) {
        print("\(k):\(v)")
    }
    
    0 讨论(0)
  • 2020-12-18 13:27

    Simple solution for Swift 4 and above...

    let dict = ["Museum1":8785.8971799638,
                "Museum2":34420.9643422388,
                "Museum3":826.467789130732,
                "Museum4":304120.342151219]
    
    let dictSortByValue = dict.sorted(by: {$0.value < $1.value} )
    
    for item in dictSortByValue {
       print("\(item.key) \(item.value) ")
    }
    
    // Museum3 826.467789130732 
    // Museum1 8785.8971799638 
    // Museum2 34420.9643422388 
    // Museum4 304120.342151219 
    

    Apparently you can sort a Dictionary in Swift 4--no need to transform into an Array.

    0 讨论(0)
提交回复
热议问题