You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何`public typealias AnyObject`可使AnyObject成为协议?

Understanding Swift's AnyObject Special Case

Great question! Let's unpack these two confusing points about AnyObject—it's definitely one of those Swift features that looks like regular code but has special handling under the hood.

Why AnyObject acts as a protocol even without the protocol keyword

The public typealias AnyObject you see in the interface isn't a regular type alias. This is a compiler-specific placeholder for a special built-in protocol that all class types implicitly conform to.

Swift's compiler treats AnyObject as a protocol behind the scenes, even though it's declared with typealias in the public interface. The comment above it says it all: "The protocol to which all classes implicitly conform." This is a case where the public interface uses typealias as a way to expose the concept to developers, but the actual implementation in the compiler treats it as a unique protocol that every class automatically adopts—no need for explicit conformance declarations.

Why the typealias works without = someType

Regular Swift type aliases require a right-hand side (like typealias MyInt = Int) because they're just aliases for existing types. But AnyObject is an exception to this rule baked directly into the language.

When the compiler encounters the line public typealias AnyObject (without an equals sign), it doesn't treat it as a regular type alias. Instead, it recognizes this as a special marker to associate the name AnyObject with that internal implicit protocol we talked about earlier.

Your own public typealias SomeOtherObject throws an error because it's following the standard Swift typealias rules, which don't allow empty definitions. AnyObject gets a pass because it's a core part of Swift's type system, designed to enable things like type erasure for class instances (e.g., using AnyObject to reference any class object without knowing its specific type).

To sum it up: AnyObject isn't a regular type alias—it's a language-specific construct that the compiler handles specially to represent the universal protocol for all classes.

内容的提问来源于stack exchange,提问作者Nishu_Priya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:24:01