根据“使用 Swift with Cocoa和Objective-C”iBook(在Loc 9附近)关于id兼容性: You can also call any Objective-C method and access any property without casting to a more specific class type. 书中给出的例子(如下所示)没有
You can also call any Objective-C method and access any property without casting to a more specific class type.
书中给出的例子(如下所示)没有编译,这似乎与上述陈述相矛盾.根据该书,下面的最后一行不应该执行,因为NSDate对象上不存在length属性.
var myObject: AnyObject = UITableViewCell() myObject = NSDate() let myLength = myObject.length?
相反,这无法编译为“无法找到接受提供的参数的’length’的重载”最后一行的错误.
这是一个错误,一个错字,还是关于调用任何Objective-C方法错误的声明?
编译器错误是说length是一个函数,你用不正确的参数调用它你可以做myObject.length?()返回nil
还有myObject.count?会给你零,没有编译错误
xcrun swift Welcome to Swift! Type :help for assistance. 1> import Cocoa 2> var obj : AnyObject = NSDate() obj: __NSDate = 2014-06-25 13:02:43 NZST 3> obj.length?() $R5: Int? = nil 4> obj.count? $R6: Int? = nil 5> obj = NSArray() 6> obj.length?() $R8: Int? = nil 7> obj.count? $R9: Int? = 0 8>
我认为编译器正在做的是搜索所有调用length的方法和属性,它发现一些类提供了length()但没有类提供长度,因此错误消息.就像在ObjC中调用[obj nonexistmethod]时一样,编译器会给出错误,说即使你在id类型对象上调用它也不存在nonxistmethod
如果您尝试在Swift中调用不存在的方法,就会发生这种情况
14> obj.notexist? <REPL>:14:1: error: 'AnyObject' does not have a member named 'notexist' obj.notexist? ^ ~~~~~~~~ 14> obj.notexist?() <REPL>:14:1: error: 'AnyObject' does not have a member named 'notexist()' obj.notexist?() ^ ~~~~~~~~