我还发现,如果将Swift类基于NSObject,则会看到一些意外的运行时行为,该行为可能会隐藏编码错误。这是一个例子。
在此示例中,在我们不基于NSObject的情况下,编译器正确地在testIncorrect_CompilerShouldSpot中发现了错误,并报告“ ...'MyClass'无法转换为'MirrorDisposition'”
class MyClass {
let mString = "Test"
func getAsString() -> String {
return mString
}
func testIncorrect_CompilerShouldSpot() {
var myString = "Compare to me"
var myObject = MyClass()
if (myObject == myString) {
// Do something
}
}
func testCorrect_CorrectlyWritten() {
var myString = "Compare to me"
var myObject = MyClass()
if (myObject.getAsString() == myString) {
// Do something
}
}
}
在此示例中,我们基于NSObject,编译器未在testIncorrect_CompilerShouldSpot中发现错误:
class myClass : NSObject {
let mString = "Test"
func getAsString() -> String {
return mString
}
func testIncorrect_CompilerShouldSpot() {
var myString = "Compare to me"
var myObject = MyClass()
if (myObject == myString) {
// Do something
}
}
func testCorrect_CorrectlyWritten() {
var myString = "Compare to me"
var myObject = MyClass()
if (myObject.getAsString() == myString) {
// Do something
}
}
}
我想这是道德的,仅基于您真正必须使用的NSObject!