Create an array of heights in metric and imperial for UIPickerView?

I am trying to populate with UIPickerViewparameters using a static variable. Is there a faster way to create a list of metric heights instead of a for loop?

Here is what I got:

static var heightMetric: [(key: String, value: String)] {
    var items: (key: String, value: String) = []

    for item in 30...330 {
        items.append(("\(item)", "\(item) cm"))
    }

    return items
}

For an imperial form, any idea on how to create a list of options in a format 5' 8"to fill out UIPickerView?

+4
source share
1 answer

No need for for-loop:

static var heightMetric: [(key: String, value: String)] = {
    return (30...330).map {
        ("\($0)", "\($0) cm")
    }
}()

You can even remove the explicit type and just write static var heightMetric = { ...

, . , , map, , % . :

static var heightMetricImperial = {
    return (12...120).map {
        ("\($0)", "\($0 / 12)' \($0 % 12)\"")
    }
}()

:

class K {
    static var heightMetric = {
        (30...330).map {
            ("\($0)", "\($0) cm")
        }
    }()

    static var heightMetricImperial = {
        (12...120).map {
            ("\($0)", "\($0 / 12)' \($0 % 12)\"")
        }
    }()
}

print(K.heightMetric)
print(K.heightMetricImperial)
+4

All Articles