Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the statement "public typealias AnyObject" make AnyObject a protocol?

Tags:

ios

swift

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?

like image 226
Nishu_Priya Avatar asked Feb 09 '19 05:02

Nishu_Priya


People also ask

How to use AnyObject in Swift?

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.

When to use AnyObject in Swift?

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.

What is AnyObject Swift?

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.


1 Answers

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

like image 108
SIlvester Avatar answered Nov 15 '22 11:11

SIlvester