1

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.

ajrlewis
  • 2,968
  • 3
  • 33
  • 67
  • @OlegGordiichuk I thought that they were classes? "The NSUnitVolume class is an Dimension subclass that encapsulates units of measure for volume." – ajrlewis Mar 16 '17 at 09:34

2 Answers2

2

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"]
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100
1

The accepted answer works well. For completeness, this is how I used it:

var units: [Dimension] {
    return unitMasses.map({ unit in unit }) + unitLengths.map({ unit in unit })
}

var symbols: [String] {
    return units.map({ unit in unit.symbol })
}
ajrlewis
  • 2,968
  • 3
  • 33
  • 67