Swift:无法在循环内解开可选 [英] Swift: Can't unwrap an optional inside a loop

查看:119
本文介绍了Swift:无法在循环内解开可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么在这种情况下可以展开可选值:

I can't understand why unwrapping an optional value is possible in this case:

let name: String? = "Toto"
guard let name = name else { fatalError() }
print(name)

但当此代码段包装在for循环中时则不会:

but not when this snippet is wrapped in a for-loop:

for _ in 0..<100 {
  let name: String? = "Toto"
  guard let name = name else { fatalError() }
  print(name)
}

我收到错误消息定义与先前的值冲突".

I got the error "Definition conflicts with previous value".

在Xcode 11.0中使用Swift 5.

Using Swift 5 in Xcode 11.0.

推荐答案

无效,因为guard不会引入新的作用域,并且在同一作用域中不能有两个具有相同名称的变量.

is not valid because guard does not introduce a new scope, and you cannot have two variables with the same name in the same scope.

这在文件级别(即在"main.swift"中)进行编译是一个错误.显然,通过guard绑定的变量隐藏了同名的另一个变量,而与声明它们的类型和顺序无关:

That this compiles on the file level (i.e. in "main.swift") is a bug. Apparently the variable bound via guard hides the other variable of the same name, regardless of the type and the order in which they are declared:

let aName = "Toto"
guard let aName = Int("123") else { fatalError() }
print(aName) // 123

guard let bName = Int("123") else { fatalError() }
let bName = "Toto"
print(bName) // 123

已报告此错误为 SR-1804没有编译器错误,无法重新声明由警戒限制的变量.

这篇关于Swift:无法在循环内解开可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆