在Swift 5中,如何将[0,3,2,1]转换为[“三个”,“三个”,“三个”,“两个”,“两个”,“一个”]?

时间:2019-06-29 21:04:36

标签: swift

我正在尝试解决正在构建的应用程序中的问题。

我已经过滤掉并删除了零,但是我无法弄清楚如何根据数组中的Int值来复制数组值。

var array1: [Int] = [0,3,2,1]

let aboveZero = array1.filter{$0 >= 1}
print(aboveZero) // "[3, 2, 1]"

let words1 = aboveZero.map { NumberFormatter.localizedString(from: $0 as NSNumber, number: .spellOut) }
print(words1) // "["three", "two", "one"]"

预期:“ [”三个“,”三个“,”三个“,”两个“,”两个“,”一个“]”

2 个答案:

答案 0 :(得分:0)

flatMapArray.init(repeating:,count:)一起使用:

[0, 3, 2, 1].flatMap {
    repeatElement(
        NumberFormatter.localizedString(
            from: $0 as NSNumber,
            number: .spellOut
        ),
        count: $0
    )
}

答案 1 :(得分:0)

尝试一下:

var array1: [Int] = [0,3,2,1]

let aboveZero = array1.filter{$0 >= 1}
print(aboveZero)

var array2: [Int] = []
aboveZero.forEach({ for _ in 0..<$0 { array2.append($0) } })
print(array2) // ["three", "three", "three", "two", "two", "one"]

let words1 = array2.map { NumberFormatter.localizedString(from: $0 as NSNumber, number: .spellOut) }
print(words1) // ["three", "three", "three", "two", "two", "one"]