0

I have a function that converts minutes to either a decimal or a HH:MM string based on a user preference in NSUserDefaults.

For example, 90 minutes would be either 1.5 or 1:30.

Here's my function:

func decimalOrHHMM(value:Int) -> String{
  let totalMinutes = Double(value)

  let defaults = UserDefaults.standard
  if defaults.string(forKey: "displayTotalsAs") == "hhmm"{
    //HH:MM
    let hours = floor(totalMinutes/60)
    let minutes = totalMinutes.truncatingRemainder(dividingBy: 60) //This gives us the remainder
    let hrs = String(format: "%.0f", hours) //Remove tenths place
    var mins = ""
    if minutes < 10{
      //Prepend 0
      mins = String(format: "0%.0f", minutes)
    }else{
      mins = String(format: "%.0f", minutes)
    }
    return "\(hrs):\(mins)"
  }else{
    //Decimal
    return String(format: "%.1f", totalMinutes/60)
  }
}

This works great, but I'm wondering if this can be converted to an NSNumberFormatter Swift extension somehow. I'm having trouble knowing what I need to override in order to do all the converting.

Any idea how I can make this an extension?

Clifton Labrum
  • 13,053
  • 9
  • 65
  • 128

1 Answers1

0

This is the basic structure for a Swift extension, you could use a function instead of a computed property, but since your original function takes an Int value, a computed property makes sense.

extension Int {
    var decimalOrHHMM: String {
        return "\(self)" // do your actual conversion here
    }
}

You can also choose to extend NSNumberFormatter.

par
  • 17,361
  • 4
  • 65
  • 80
  • Thanks, that makes sense. How would it look with an `NSNumberFormatter` extension? I need to use that because I'm passing it in to a graph plugin that only accepts `NSNumberFormatter` for changing the graph's labels. – Clifton Labrum Nov 10 '16 at 05:55
  • Just replace `extension Int` with `extension NSNumberFormatter` and realize `self` will be an `NSNumberFormatter` instead of an `Int`. Give it a try and if you get stuck with something specific ask another question. – par Nov 10 '16 at 06:10