Variadic Zip Function in Swift

后端 未结 2 820
[愿得一人]
[愿得一人] 2021-01-15 19:47

Variadic Zip Function

Swift 4.1, Xcode 9.4

I have been using Apple\'s native zip(_:_:) recently and I ran into a situation whereby I needed

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-15 20:23

    Sadly, this is not completely possible in Swift since we can't have different Array types for Variadic parameters. A possible work around would be to convert all arrays to type [Any], and then zip them all together which forms an array array, and than using map, converting the arrays to the wanted tuple using force casting. The solution might be bit dirty but not all too complicated.

    extension Sequence {
    
        //easy conversion of any sequence to [Any]
        var untyped:[Any] {
            return self as! [Any]
       }
    }
    
    func zip(_ untypedSequences:[Any]...) -> [[Any]] {
        let count = untypedSequences.map{$0.count}.min() ?? 0
        return (0..

提交回复
热议问题