Why does Swift allow me to call setTitle on AnyObject?

@IBAction func helloClick(sender: AnyObject) { sender.setTitle("Click", forState: UIControlState.Normal) } 

The above code is working fine. But is setTitle not a method on AnyObject ? Isn't that a compile-time error?

+6
source share
2 answers

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

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

This will simplify the interaction of Objective-C.

The manual also states the following:

However, since the specific type of the object introduced as AnyObject is unknown before execution, it is possible to inadvertently write unsafe code.

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

+4
source

AnyObject behaves similar to Objective-C id

It allows you to call any method. The goal of AnyObject is to bypass compile-time errors. You can call any method on AnyObject and it will compile in order. You will see errors at runtime.

In documents

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

+3
source

Source: https://habr.com/ru/post/975535/


All Articles