DisplayName
DisplayName

Reputation: 37

Round up to nearest integer key value in dictionary [Swift / iOS]

I have a basic dictionary list similar to this:

let fanFlow:  [Int: String] = [100: "25 m/s", 350: "34 m/s", 420: "42 m/s"]

I'm trying to make it so that if I have a value in the middle of those figures, it will round up to the next highest number integer in the dictionary list.

For example: If I have a value "250", it will round that up to the next figure in the list, which will be "350", returning back "34 m/s".

Tried to google this and couldn't find anything that could help me. Any help would be great!

Thanks!

Upvotes: 1

Views: 528

Answers (2)

oisdk
oisdk

Reputation: 10091

How about:

let fanFlow = [100: "25 m/s", 350: "34 m/s", 420: "42 m/s"]

func nextHighest(n: Int) -> String? {
  return fanFlow
    .keys
    .filter { $0 > n }
    .minElement()
    .map { fanFlow[$0]! }
}

nextHighest(250) // "34 m/s"

Or, in Swift 1.2:

let fanFlow = [100: "25 m/s", 350: "34 m/s", 420: "42 m/s"]

func nextHighest(n: Int) -> String? {

  let higher = fanFlow.keys.filter { $0 > n }.array

  return higher.isEmpty ? nil : fanFlow[minElement(higher)]!

}

Upvotes: 3

Leo Dabus
Leo Dabus

Reputation: 236420

let fanFlow:  [Int: String] = [100: "25 m/s", 350: "34 m/s", 420: "42 m/s"]
let fanFlowKeys = fanFlow.keys.array.sorted(<)

func getFanFlow(input:Int) -> String {
    for key in fanFlowKeys {
        if input <= key {
            return fanFlow[key]!
        }
    }
    return ""
}

getFanFlow(250)    // "34 m/s"

Upvotes: 2

Related Questions