简体   繁体   中英

Sorting a Dictionary by Double value Swift

I have a Firebase database with place names and coordinates, having fetched both and putting each of them into their own Array and then into a Dictionary , I want the Dictionary sorted by the nearest location/lowest Double .

I have looked at tonnes of previously asked questions and just can't seem to figure out what I'm doing wrong. When I print my dictionary it orders them in alphabetical order (having crosschecked the (actual) distances I know they are correct).

How would I order by lowest Double ?

var placeName = ""
var distanceArray = [Double]()
var nameDistanceDictionary = [String:Double]()

Inside fetching data from Firebase

self.placeName = placeSnap.key

let distanceRound = Double(round(10*distance)/10)
self.distanceArray.append(distanceRound)
self.nameDistanceDictionary = [self.placeName:distanceRound]
print(self.nameDistanceDictionary)


//Prints (example Doubles)
["Ascot": 5.5]
["Birmingham": 1.2]
["Bristol" : 18.6]
["London": 0.3]
["Manchester": 40.2]
["Newcastle": 2.4]

I've tried (This prints the same as above minus the [""]

for (k,v) in (Array(self.nameDistanceDictionary).sorted {$0.1 < $1.1}) {
    print("\(k):\(v)")
    }

Every item in your dictionary has two properties: key and value ( more about dictionary here )

You don't have to create Array from your dictionary. Just sort your dictionary by item value.

.sorted(by: {$0.value < $1.value})

now create for each loop and instead of creating k and v just create item which will represent each item in your dictionary.

for item in ...

Now if you want to print value and also the key just use

print(item.value)

and

print(item.key)

Replace whole for each loop:

for (k,v) in (Array(self.nameDistanceDictionary).sorted {$0.1 < $1.1}) {
    print("\(k):\(v)")
}

with this

for item in nameDistanceDictionary.sorted(by: {$0.value < $1.value}) {
    print("\(item.key):\(item.value)")
}

Your life would be a lot easier if you stored your model as a struct instead of trying to do some Dictionary hack. Try something like this:

struct Place {
    let name: String
    let distance: Double
}

let places = [Place(name: "Ascot", distance: 5.5),
              Place(name: "Birmingham", distance: 1.2),
              Place(name: "Bristol", distance: 18.6),
              Place(name: "London", distance: 0.3),
              Place(name: "Manchester", distance: 40.2),
              Place(name: "Newcastle", distance: 2.4)]

for place in places.sorted(by: { $0.distance < $1.distance }) {
    print(place.name)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM