How to represent magnitude for mass in Swift?

后端 未结 3 918
甜味超标
甜味超标 2021-01-06 13:31
// SI units
enum Magnitude : Measurement {
    case Milli = Measurement(-3, \"ml\")
    case Centi = Measurement(-2, \"cl\")
    case Desi = Measurement(-1, \"dl\")
         


        
3条回答
  •  被撕碎了的回忆
    2021-01-06 14:08

    Did you consider using a dictionary? For example:

    let magnitudes: [String: Double] = [
        "ml": -3,
        "cl": -2,
        "dl": -1,
        "g": 0,
        "kg": 3
    
    ]
    
    // list all units:
    println(", ".join(magnitudes.keys)) // kg, g, ml, cl, dl
    
    
    // convert
    func convert(from: String, to: String, value: Double) -> Double{
        let mag1 = __exp10(magnitudes[from]!)
        let mag2 = __exp10(magnitudes[to]!)
        return value * mag1 / mag2
    }
    
    
    let result = convert("dl", "ml", 3.0)
    println(result) // 300.0
    

提交回复
热议问题