Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Swift let me call setTitle on AnyObject?

Tags:

swift

cocoa

@IBAction func helloClick(sender: AnyObject) {

    sender.setTitle("Click", forState: UIControlState.Normal)

}

The above code works fine. But setTitle isn't a method on AnyObject? Shouldn't this be a compile time error?

like image 286
Ian Warburton Avatar asked Sep 19 '14 13:09

Ian Warburton


2 Answers

This is part of the language specification (see the section on id compatibility)

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

This is to allow for easier Objective-C interop.

The guide also states the following:

However, because the specific type of an object typed as AnyObject is not known until runtime, it is possible to inadvertently write unsafe code.

Obviously as the validity of your code is only determined at runtime, this can be unsafe.

like image 80
ColinE Avatar answered Oct 14 '22 18:10

ColinE


AnyObject behaves similarly to Objective-C's id

It allows any method to be called on it. The purpose of AnyObject is to bypass compile time errors. You can call any method on an AnyObject and it will compile fine. You will only see errors in runtime.

Per the docs,

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

like image 39
Zaid Daghestani Avatar answered Oct 14 '22 19:10

Zaid Daghestani