When executed in the playground, the following piece of code causes a 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
.
When you use optional binding you can omit the explicit checking for nil
.
func greet(person: [String:String]?, age: Int?) {
guard let name = person?["name"] else {
return
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.