When I pressed Command and clicked AnyObject
to navigate to the interface of the AnyObject
, I came across the below definition:
public typealias AnyObject
I see this comment written above the definition:
The protocol to which all classes implicitly conform.
Well I don't understand how this definition makes AnyObject
a protocol
without explicitly using the keyword protocol
.
Also, it's a typealias
without = someType
, which is an invalid statement.
I can't write a statement like:
public typealias SomeOtherObject
It gives a compilation error.
Can anyone explain what exactly is happening here?
You use AnyObject when you need the flexibility of an untyped object or when you use bridged Objective-C methods and properties that return an untyped result. AnyObject can be used as the concrete type for an instance of any class, class type, or class-only protocol.
AnyObject can also be used as the concrete type for an instance of a type that bridges to an Objective-C class. Many value types in Swift bridge to Objective-C counterparts, like String and Int . The flexible behavior of the AnyObject protocol is similar to Objective-C's id type.
Any and AnyObject are two special types in Swift that are used for working with non-specific types. According to Apple's Swift documentation, Any can represent an instance of any type at all, including function types and optional types. AnyObject can represent an instance of any class type.
The thing is that by pressing on AnyObject
holding CMD
you will not actually see source code, but just a public
interface. If you will go deep into Swift source code you will actually find out that
public typealias AnyObject
is actually looks like this:
public typealias AnyObject = Builtin.AnyObject
Here is the link to file containing this code https://github.com/apple/swift/blob/master/stdlib/public/core/Policy.swift
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