Search code examples
arraysswiftanyobject

Combining UnitMass and UnitLength arrays


I'm trying to combine two measurement arrays:

var unitMasses: [UnitMass] {
    return [.milligrams, .grams, .kilograms, .ounces, .pounds]
}

var unitLengths: [UnitLength] {
    return [.centimeters, .decimeters, .meters]
}

into one:

var units: [AnyObject] {
    // This works:
    return [unitMasses].flatMap{$0}
    // But I've tried the following and this doesn't:
    //return ([unitMasses as AnyObject] + [unitVolumes as AnyObject]).flatMap{$0}
}

I want to be able able to to access the .symbol attribute of the elements in the units variable:

var symbols: [String] {
    return units.map({ unit in unit.symbol })
}

Thanks.


Solution

  • From my point of view this way is quite more straight forward.I do not see any needs to merge arrays before.

    var symbols = unitMasses.map({$0.symbol})
    symbols += unitLengths.map({$0.symbol})
    
    print(symbols) // ["mg", "g", "kg", "oz", "lb", "cm", "dm", "m"]