var a: String? = "A"var b: String? // nilif let (m,n) = (a,b) { println("m: \(m),n: \(n)")} else { println("too bad")}// error: Bound value in a conditional binding must be of Optional type// this of course is because the tuple itself is not an Optional// let's try that to be sure that's the problem...let mysteryTuple: (String?,String?)? = (a,b)if let (m,n) = mysteryTuple { println("m: \(m),n: \(n)")} else { println("too bad")}// yeah,no errors,but not the behavior I want (printed "m: A,n: nil")// and in a different way:if let m = a,n = b { println("m: \(m),n: \(n)")} else { println("too bad")}// a couple Syntax errors (even though 'let m = a,n = b'// works on its own,outsIDe the if statement)
这甚至可能吗?如果不是(我猜),你认为Apple将来(或应该)将来实施这个吗?
在决定是否可能之前,请考虑为什么if – let … conditionals使用单个可选值:此代码编译的原因if let constvar = testvar { ...}
是所有可选类型都符合LogicalValue协议,该协议处理可选值的空检查.
这解释了为什么使用可选元组的技巧也不起作用:如果元组本身是非null,则检查LogicalValue的实现,忽略其组件. Apple决定背后的逻辑很明确:当元组的所有元素类型都是可选的时,它们不是为元组做例外,而是采用统一的方法,并以与处理其他可选类型相同的方式处理元组.
当然,通过额外的代码行实现您尝试实现的逻辑很容易:
if a != nil && b != nil { let (m,n) = (a!,b!) println("m: \(m),n: \(n)")} else { println("too bad")}总结
以上是内存溢出为你收集整理的swift:if-let并行赋值全部内容,希望文章能够帮你解决swift:if-let并行赋值所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)