TruMan1 TruMan1 - 6 months ago 43
iOS Question

Create height array in metric and imperial for UIPickerView?

I'm trying to fill a

UIPickerView
with options using a static variable. Is there a more swifty way in creating a list of metric height instead of a for-loop?

Here's 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 the imperial form, any idea on a good way to create the list of options in a format as
5' 8"
to fill a
UIPickerView
?

Answer

No need for the for-loop actually:

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

You can even drop the explicit type and simply write static var heightMetric = { ...

Regarding the foot and inch form I do not know of any built-in functionality for that. You either have to calculate the value based on the centimeter value by doing a little bit of math or create a map similar to the above one where you might make use of the % operator to split the number into feet and inches. For example:

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

Complete example:

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)