[英]Why does Swift give me an EXC_BAD_INSTRUCTION here?
When executed in the playground, the following piece of code causes a EXC_BAD_INSTRUCTION
: 在操场上执行时,以下代码导致EXC_BAD_INSTRUCTION
:
func greet(person: [String:String]?, age: Int?) {
guard let name = person!["name"] where person != nil else {
return
}
}
greet(nil, age: nil)
Can anyone tell me what's going on? 谁能告诉我怎么回事?
The exclamation mark after person
unwraps the optional which causes the crash because person
is nil
. person
解开包装后的感叹号,因为person
nil
导致崩溃。
When you use optional binding you can omit the explicit checking for nil
. 使用可选绑定时,可以省略对nil
的显式检查。
func greet(person: [String:String]?, age: Int?) {
guard let name = person?["name"] else {
return
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.