swift - 在 Swift 闭包中解压嵌套元组

标签 swift

如果你有:

let array = [(1, 2)]

你可以这样做:

array.map({ first, second in ... })

如果你有:

let array = [((1, 2), (3, 4))]

如何解压?

array.map({ (first, second), (third, fourth) in ... })
array.map({ ((first, second), (third, fourth)) in ... })

这些都不编译。

最佳答案

这可行,但不是很漂亮

let array = [((1, 2), (3, 4))]

array.map({ a, b in
    return a.0 + a.1 + b.0 + b.1
})

这可能会好一点,但它仍然是嵌套的

let array = [((1, 2), (3, 4))]

array.map({ (a:(first:Int, second:Int), b:(first:Int, second:Int)) in
    return a.first + a.second + b.first + b.second
})

您可以使用 map 将它们缩减为元组,然后分配值

array.map{($0.0,$0.1,$1.0,$1.1)}.map { (first:Int, second:Int, third:Int, forth:Int) in }

关于swift - 在 Swift 闭包中解压嵌套元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33373319/

相关文章:

swift - "let-in" block 在 Swift 中意味着什么?

ios - Xcode 如何在水平堆栈 View 中创建方形按钮(宽度等于高度)

ios - 如何在 ARKit 中获取一些有用的传感器数据?

swift - 如何从 NSDictionary swift 4 获取关键数据

iOS - UINavigationController,隐藏导航栏

swift - 在 Alamofire 4 中动态允许自签名证书

xcode - 物理物体与另一个物理物体碰撞

swift - 通过 NSUserDefaults Swift 2.0 检索数据

ios - 从另一个 View 调用 UITableView 函数

objective-c - 使用 objective-c 文件创建 swift cocoa touch 框架