@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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With