在Implement Navigation开始篇Developing iOS Apps (Swift) Apple的教程,有以下代码片段:
if let sourceViewController = sender.sourceViewController as? MealViewController,
meal = sourceViewController.meal {}
本教程使用 Swift 3.1,此代码段似乎对我不起作用。仅当我在 meal = sourceViewController.meal
前面加上 let
关键字时它才有效,如下所示:
if let sourceViewController = sender.sourceViewController as? MealViewController,
let meal = sourceViewController.meal {}
我的问题纯粹出于好奇:if let a = b, c = d
在任何 Swift 版本中是否曾经是有效语法?
最佳答案
是的,以下代码使用 Xcode 8 和“传统模式”(即 swift 2.3):
let a: Int? = 1
let b: Int? = 2
if let x = a, y = b { }
从 Swift 3 开始,它必须写成
if let x = a, let y = b { }
由于 SE-0099 Restructuring Condition Clauses ,特别是(强调):
The root problem lies in the condition grammar: commas are used both to separate items within a clause (e.g. in
if let x = a, y = b {
) and to separate mixed kinds of clauses (e.g.if let x = a, case y? = b {
). This proposal resolves this problem by retaining commas as separators between clauses (as used elsewhere in Swift) and limits clauses to single items.
关于swift - if let 可以在 Swift 3.1 中以逗号分隔吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45258258/