Skip to content

Instantly share code, notes, and snippets.

@tomlokhorst
Created March 4, 2015 18:29
Show Gist options
  • Save tomlokhorst/dd6cc06288881f27d8bd to your computer and use it in GitHub Desktop.
Save tomlokhorst/dd6cc06288881f27d8bd to your computer and use it in GitHub Desktop.
Invalid cast causing runtime crash in Swift <= 1.2
import Foundation
let obj = NSNumber(int: 2)
func correct<T>() -> T? {
if let val = obj as? T {
println("matching types")
return val
}
else {
println("not matching")
}
return nil
}
func incorrect<T : NSObject>() -> T? {
if let val = obj as? T {
println("matching types")
return val
}
else {
println("not matching")
}
return nil
}
correct() as NSString? // prints "not matching"
incorrect() as NSString? // prints "matching types"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment