JefferyRPrice
JefferyRPrice

Reputation: 895

Can you really call any Objective-C method on AnyObject?

According to the "Using Swift with Cocoa and Objective-C" iBook (near Loc 9) regarding id compatibility:

You can also call any Objective-C method and access any property without casting to a more specific class type.

The example given in the book (shown below) does not compile, which seems to contradict the above statement. According to the book, the last line below should not execute because the length property does not exist on an NSDate object.

var myObject: AnyObject = UITableViewCell()
myObject = NSDate()
let myLength = myObject.length?

Instead, this fails to compile with a "Could not find an overload for 'length' that accepts the supplied arguments" error on the last line.

Is this a bug, a typo, or is the statement about calling any Objective-C method wrong?

Upvotes: 4

Views: 888

Answers (1)

Bryan Chen
Bryan Chen

Reputation: 46608

the compiler error is saying length is a function and you call it with incorrect arguments

you can do myObject.length?() which return nil

also myObject.count? will give you nil without compile error

 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>

I think what compiler was doing is search all method and property that called length, it found some class provide length() but no class provide length, hence the error message. Just like when you call [obj nonexistmethod] in ObjC, compiler will give your error saying nonexistmethod does not exist even you call it on id type object

This is what happened if you try to call non-exist method in 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?()
^   ~~~~~~~~

Upvotes: 1

Related Questions