在Swift中展开一个arrays数组
Swift中是否有一个对手在Scala,Xtend,Groovy,Ruby等公司中扮演angular色?
var aofa = [[1,2,3],[4],[5,6,7,8,9]] aofa.flatten() // shall deliver [1,2,3,4,5,6,7,8,9]
当然,我可以使用减less,但有点糟糕
var flattened = aofa.reduce(Int[]()){ a,i in var b : Int[] = a b.extend(i) return b }
Swift 3.0
reduce
:
let numbers = [[1,2,3],[4],[5,6,7,8,9]] let reduced = numbers.reduce([], +)
flatMap
:
let numbers = [[1,2,3],[4],[5,6,7,8,9]] let flattened = numbers.flatMap { $0 }
joined
:
let numbers = [[1,2,3],[4],[5,6,7,8,9]] let joined = Array(numbers.joined())
自Swift 2.0以来,为CollectionType
协议实现了flatten
(或joined
Swift 3)方法:
let numbers = [[1,2,3],[4],[5,6,7,8,9]] let flattened = Array(numbers.flatten())
在某些情况下, flatten()
可能是有益的,因为它返回的是lazy collection而不是array,但是在传递给Array()
时总是可以转换为数组。
这对我工作:
let numbers = [[1, 2, 3], [4, 5, 6]] let flattenNumbers = numbers.reduce([], combine: +)
另一个更通用的实现reduce
,
let numbers = [[1,2,3],[4],[5,6,7,8,9]] let reduced = reduce(numbers,[],+)
这完成了同样的事情,但可以更深入地了解reduce
。
从苹果的文档,
func reduce<S : SequenceType, U>(sequence: S, initial: U, combine: (U, S.Generator.Element) -> U) -> U
描述
依次返回初始化为初始化的累加值和序列的每个元素的重复调用结果。
将flatten()重命名为joined()。
https://github.com/apple/swift-evolution/blob/master/proposals/0133-rename-flatten-to-joined.md