我在游乐场中编写了以下代码并且工作正常,但它看起来有点乱。在Swift中有更简洁的方法吗?
我想要一个字符串如下所示: 1,12,2,12,3,12,1,13,5,13,6,13,7,14,8,14
我不知道每个数组中有多少值,数组可能不是偶数倍,但我知道每个array2值的3个array1值的关系
let array1 = [1,2,3,4,5,6,7,8] //sample 1st array
let array2 = [12,13,14] //sample 2nd array
let relationshipInterval = 3
let remainder = (array1.count % relationshipInterval)
let multiples = (array1.count - remainder)/relationshipInterval
var string = ""
var array1Start = 0
var array1End = relationshipInterval-1
var array2Value = 0
for _ in 1...multiples {
for array1value in array1[array1Start...array1End] {
string += "\(array1value), "
string += String(array2[array2Value])+", "
}
array1Start = array1End + 1
array1End = array1Start + relationshipInterval - 1
array2Value += 1
}
for array1value in array1[array1Start...array1Start+remainder-1] {
string += "\(array1value), "
string += String(array2[array2Value])+", "
}
print (string) //prints 1, 12, 2, 12, 3, 12, 4, 13, 5, 13, 6, 13, 7, 14, 8, 14
答案 0 :(得分:3)
我不确定这是否涵盖了所有用例,但使用zip
,flatMap
和joined
只需一步即可完成此操作!
let array1 = [1,2,3,4,5,6,7,8]
let array2 = [12, 13, 14]
let text = zip(array1, array2.flatMap({ [$0, $0, $0] }))
.flatMap({ [$0, $1] })
.map({ String($0) })
.joined(separator: ", ")
// text -> "1, 12, 2, 12, 3, 12, 4, 13, 5, 13, 6, 13, 7, 14, 8, 14"
这里的单行分为四个步骤,以便更清楚每个阶段发生的事情:
// 1. create an array with each element in array2 is trippled:
let trippled = array2.flatMap({ item in
return [item, item, item]
})
// trippled -> [12, 12, 12, 13, 13, 13, 14, 14, 14]
// 2. zip array1 with the trippled array:
let zipped = zip(array1, trippled)
// zipped -> Zip2Sequence(_sequence1: [1, 2, 3, 4, 5, 6, 7, 8], _sequence2: [12, 12, 12, 13, 13, 13, 14, 14, 14])
// 3. flatten the zipped aray
let combined = zipped.flatMap({ leftItem, rightItem in
return [leftItem, rightItem]
})
// combined -> [1, 12, 2, 12, 3, 12, 4, 13, 5, 13, 6, 13, 7, 14, 8, 14]
// 4. tranform to a string
let text = combined.map({ item in
return "\(item)"
}).joined(separator: ", ")
// text -> "1, 12, 2, 12, 3, 12, 4, 13, 5, 13, 6, 13, 7, 14, 8, 14"