Swift sort dictionary by value

前端 未结 3 989
眼角桃花
眼角桃花 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: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.

提交回复
热议问题