Flatten [Any] Array Swift

时间:2017-11-29 03:41:05

标签: arrays swift

使用this Stack Overflow问题我有以下代码。

str1.substring(1, str1.length() - 1)

而不是将展平设置为let numbers = [1,[2,3]] as [Any] var flattened = numbers.flatMap { $0 } print(flattened) // [1, [2, 3]] ,而不是将其设为[1, [2, 3]]

在Swift中实现这一目标的最简单/最简洁的方法是什么?

3 个答案:

答案 0 :(得分:5)

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"]

答案 1 :(得分:4)

可能有更好的方法来解决这个问题,但一种解决方案是将自己的扩展编写到Array:

</head>
<body>
    <p>
        <h1 style="display: inline;">Dean Mysliwiec</h1>
      &nbsp &nbsp &nbsp &nbsp &nbsp
      &nbsp &nbsp &nbsp &nbsp &nbsp
      &nbsp &nbsp &nbsp &nbsp &nbsp
      &nbsp &nbsp &nbsp &nbsp &nbsp
  <a href="index.html" class="main">Home Page</a>
        <a href="photos.html" class="main">Photography</a>
----- and so on.

输出:

  

[1,2,4,5,3,“嗨”]

此解决方案将处理任何数组嵌套。

答案 2 :(得分:1)

这是@ rmaddy anyFlatten的替代实现:

它可以最简洁地写成这样,但它非常神秘:

extension Array {
    func anyFlatten() -> [Any] {
        return self.flatMap{ ($0 as? [Any]).map{ $0.anyFlatten() } ?? [$0] }
    }
}

这是一个更合理的实施方式:

extension Array {
    func anyFlatten() -> [Any] {
        return self.flatMap{ element -> [Any] in
            if let elementAsArray = element as? [Any] { return elementAsArray.anyFlatten() }
            else { return [element] }
        }
    }
}