Swift2 guard expression crashes
| Originator: | 654070 | ||
| Number: | rdar://22878681 | Date Originated: | 28-Sep-2015 |
| Status: | Open | Resolved: | No |
| Product: | Swift | Product Version: | 2 |
| Classification: | Bug | Reproducible: | Always |
Summary:
Swift2 guard expression crashes when subscript with unexisting key is called on AnyObject
Steps to Reproduce:
1. Start a new Swift2 project
2. Add a function to your ViewController:
func willCrashWithObject(object: AnyObject) -> AnyObject? {
guard let nested: AnyObject = object["unexisting_key"] else {
return nil
}
return nested
}
3. Add the following code to viewDidLoad method:
let _ = willCrashWithObject(["a": 5])
Expected Results:
Function should return nil
Actual Results:
Code crashes with error: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Version:
iOs 9.0
Notes:
There are 3 ways to avoid an issue:
1) Remove AnyObject:
guard let nested = object["unexisting_key"] else
2) Make it optional
guard let nested: AnyObject? = object["unexisting_key"] else
3) Pass dictionary to willCrashWithObject instead of AnyObject
Configuration:
iPhone5c
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!