如何在Swift中快速展平数组? [英] How can I flatten an array swiftily in Swift?

查看:130
本文介绍了如何在Swift中快速展平数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要转这个:

let x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

对此:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

非常优雅.

当然,最直接的方法是

var y = [Int]()
x.forEach { y.appendContentsOf($0) }

但这会使结果数组可变,这是不必要的.我不喜欢这种方式.

But that makes the resulting array mutable, which is unnecessary. I don't like this way.

我尝试使用reduce:

let y = x.reduce([Int]()) { (array, ints) -> [Int] in
    array.appendContentsOf(ints)
    return array
}

但是编译器抱怨array是不可变的,因此我不能调用变异方法appendContentsOf.

But the compiler complains that array is immutable, so I can't call the mutating method appendContentsOf.

因此,我添加了一些内容:

Hence, I added some stuff:

let y = x.reduce([Int]()) { (array, ints) -> [Int] in
    var newArr = array
    newArr.appendContentsOf(ints)
    return newArr
}

这只是普通的坏.我本能地认为这并不迅速.

This is just plain bad. I have an instinct that this is not swifty.

与上述方法相比,我如何更快地展平数组?单线将是很好.

How can I flatten an array more swiftily than the above methods? A one-liner would be good.

推荐答案

为此有一个内置函数,称为

There's a built-in function for this called joined:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]].joined()

(请注意,这实际上并不会返回另一个数组,它会返回一个FlattenBidirectionalCollection,但这通常并不重要,因为它仍然是可以与for循环一起使用的序列,没什么.如果您真的很在意, ,您可以使用Array(arrayOfArrays.joined()).)

(Note that this doesn't actually return another Array, it returns a FlattenBidirectionalCollection, but that usually doesn't matter because it's still a sequence that you can use with for loops and whatnot. If you really care, you can use Array(arrayOfArrays.joined()).)

flatMap函数也可以为您提供帮助.它的签名大致是

The flatMap function can also help you out. Its signature is, roughly,

flatMap<S: SequenceType>(fn: (Generator.Element) -> S) -> [S.Generator.Element]

这意味着您可以传递fn,对于任何元素,该fn都会返回一个序列,并且它将组合/连接这些序列.

This means that you can pass a fn which for any element returns a sequence, and it'll combine/concatenate those sequences.

由于数组的元素本身就是序列,因此可以使用一个仅返回元素本身的函数({ x in return x }或等效地只是{$0}):

Since your array's elements are themselves sequences, you can use a function which just returns the element itself ({ x in return x } or equivalently just {$0}):

[[1, 2, 3], [4, 5, 6], [7, 8, 9]].flatMap{ $0 }

这篇关于如何在Swift中快速展平数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆