展平[Any]数组迅捷 [英] Flatten [Any] Array Swift
本文介绍了展平[Any]数组迅捷的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用此堆栈溢出问题我有以下代码.
let numbers = [1,[2,3]] as [Any]
var flattened = numbers.flatMap { $0 }
print(flattened) // [1, [2, 3]]
我希望将其设置为[1, 2, 3]
,而不是将其展平.
在Swift中最简单/最干净的方法是什么?
解决方案
extension Collection {
func joined() -> [Any] {
return flatMap { ($0 as? [Any])?.joined() ?? [$0] }
}
func flatMapped<T>(with type: T.Type? = nil) -> [T] {
return joined().compactMap { $0 as? T }
}
}
let objects: [Any] = [1,[2,3],"a",["b",["c","d"]]]
let joined = objects.joined() // [1, 2, 3, "a", "b", "c", "d"]
let integers = objects.flatMapped(with: Int.self) // [1, 2, 3]
// setting the type explicitly
let integers2: [Int] = objects.flatMapped() // [1, 2, 3]
// or casting
let strings = objects.flatMapped() as [String] // ["a", "b", "c", "d"]
Using this Stack Overflow question I have the following code.
let numbers = [1,[2,3]] as [Any]
var flattened = numbers.flatMap { $0 }
print(flattened) // [1, [2, 3]]
Instead of flattened being set to [1, [2, 3]]
I want it to be [1, 2, 3]
.
What is the easiest/cleanest way to achieve this in Swift?
解决方案
extension Collection {
func joined() -> [Any] {
return flatMap { ($0 as? [Any])?.joined() ?? [$0] }
}
func flatMapped<T>(with type: T.Type? = nil) -> [T] {
return joined().compactMap { $0 as? T }
}
}
let objects: [Any] = [1,[2,3],"a",["b",["c","d"]]]
let joined = objects.joined() // [1, 2, 3, "a", "b", "c", "d"]
let integers = objects.flatMapped(with: Int.self) // [1, 2, 3]
// setting the type explicitly
let integers2: [Int] = objects.flatMapped() // [1, 2, 3]
// or casting
let strings = objects.flatMapped() as [String] // ["a", "b", "c", "d"]
这篇关于展平[Any]数组迅捷的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文