I'm not horribly new to Swift, nor to Objective-C, but I saw some odd behavior when working with an Error
subtype today that led me to dig a little deeper.
When working with an NSString
subclass (yes, the below example functions similarly for classes not based on NSObject
):
import Foundation
// Class version
class OddString : NSString {
override var description: String {
return "No way, José"
}
}
let odd = OddString()
func printIt(_ string: NSString) {
print(string.description)
}
print(odd.description)
printIt(odd)
I see what I expect to see:
No way, José
No way, José
However, when I write (what I think is) the equivalent code using a struct (Error
) instead:
import Foundation
// Struct version
struct TestError : Error {
var localizedDescription: String {
return "I am a TestError"
}
}
let explosive = TestError()
func printIt(_ error : Error) {
print(error.localizedDescription)
}
print(explosive.localizedDescription)
printIt(explosive)
I see:
I am a TestError
The operation couldn’t be completed. (SanityChecks.TestError error 1.)
This is really confusing to me. Is it deciding at compile time what method will be invoked on the struct passed in to printIt
, regardless of what type it actually is?
Further: Is this difference in runtime behavior between classes and structs documented in the Swift Programming Guide, and can someone reference the section? I haven't found anything on this yet.