OGeek|极客世界-中国程序员成长平台

标题: ios - 扩展 where 子句中的 ArrayType [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 17:27
标题: ios - 扩展 where 子句中的 ArrayType

enter image description here

extension Array where Element: _ArrayType, Element.Generator.Element: Any {
    func transpose() -> [Element] {
        if self.isEmpty { return [Element]() }
        let count = self[0].count
        var out = [Element](repeating: Element(), count: count)
        for outer in self {
            for (index, inner) in outer.enumerated() {
                out[index].append(inner)
            }
        }
        return out
    }
}

从 Swift 2.2 转换后,我在 Swift 3.0 中遇到此错误。数组的元素也是数组。那么在 Swift 3.0 中如何定义呢?



Best Answer-推荐答案


extension Array where Element : Collection, Element.Index == Int, Element.IndexDistance == Int {
    func transpose() -> [[Element.Iterator.Element]] {
        typealias InnerElement = Element.Iterator.Element
        if self.isEmpty { return [] }
        let count = self[0].count
        var out = [[InnerElement]](repeating: [InnerElement](), count: count)
        for outer in self {
            for (index, inner) in outer.enumerated() {
                out[index].append(inner)
            }
        }
        return out
    }
}

关于ios - 扩展 where 子句中的 ArrayType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39366534/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://ogeek.cn/) Powered by Discuz! X3.4