在Swift中有没有对应的Scala、Xtend、Groovy、Ruby等等?

var aofa = [[1,2,3],[4],[5,6,7,8,9]]
aofa.flatten() // shall deliver [1,2,3,4,5,6,7,8,9] 

当然我可以用reduce来做,但那有点糟糕

var flattened = aofa.reduce(Int[]()){
    a,i in var b : Int[] = a
    b.extend(i)
    return b
}

当前回答

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

描述

返回反复调用combine的结果,并依次返回初始化为initial的累积值和sequence的每个元素。

其他回答

斯威夫特5.1

public extension Array where Element: Collection {

    func flatten() -> [Element.Element] {
        return reduce([], +)
    }
}

如果你也想在Dictionary值中使用它:

public extension Dictionary.Values where Value : Collection {
    func flatten() -> [Value.Element]{
         return self.reduce([], +)
    }
}

编辑:使用joined()代替:

https://developer.apple.com/documentation/swift/sequence/2431985-joined

最初的回答:

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

描述

返回反复调用combine的结果,并依次返回初始化为initial的累积值和sequence的每个元素。

修改了@RahmiBozdag的回答, 1. 公共扩展中的方法是公共的。 2. 删除了额外的方法,因为开始索引将始终为零。 3.我没有找到一种方法把compactMap内部为nil和可选的,因为内部方法T总是[Any?],欢迎提出任何建议。

 let array = [[[1, 2, 3], 4], 5, [6, [9], 10], 11, nil] as [Any?]

 public extension Array {

 func flatten<T>(_ index: Int = 0) -> [T] {
        guard index < self.count else { 
            return [] 
        }

        var flatten: [T] = []

        if let itemArr = self[index] as? [T] {
            flatten += itemArr.flatten()
        } else if let element = self[index] as? T {
            flatten.append(element)
        }
        return flatten + self.flatten(index + 1)
   }

}

let result: [Any] = array.flatten().compactMap { $0 }
print(result)
//[1, 2, 3, 4, 5, 6, 9, 10, 11]

你可以用下面的方法来平嵌套数组:

var arrays = [1, 2, 3, 4, 5, [12, 22, 32], [[1, 2, 3], 1, 3, 4, [[[777, 888, 8999]]]]] as [Any]

func flatten(_ array: [Any]) -> [Any] {

    return array.reduce([Any]()) { result, current in
        switch current {
        case(let arrayOfAny as [Any]):
            return result + flatten(arrayOfAny)
        default:
            return result + [current]
        }
    }
}

let result = flatten(arrays)

print(result)

/// [1, 2, 3, 4, 5, 12, 22, 32, 1, 2, 3, 1, 3, 4, 777, 888, 8999]