使用类型作为值,为什么这里需要"self"关键字?

Using type as a value, why is the "self" keyword required here?

我目前正在学习将类型作为函数中的一个值,并编写了这个示例代码来尝试:

import Foundation

class Animal {
    func sound() {
        print("Generic animal noises")
    }
}

func foo(_ t:Animal) {
    print("Hi")
}

foo(Animal) //Cannot convert value of type 'Animal.Type' to expected argument type 'Animal'

我对这个结果并不感到惊讶。 显然,您不能将类型本身作为参数传递给需要该类型实例的地方。但是请注意,编译器说我传递的参数是 Animal.Type 类型。所以如果我这样做,它应该编译正确吗?

func foo(_ t:Animal.Type) {
    print("Hi")
}

foo(Animal) //Expected member name or constructor call after type name

这让我很困惑,编译器告诉我它的类型是 Animal.Type *但在进行此更改后它再次显示错误.

当然我听取了 Swift 的修复建议并做了:

foo(Animal.self) //Works correctly

但我最大的问题是:为什么? Animal 本身不是类型吗?为什么编译器要求我使用 Animal.self 来获取类型?这真的让我很困惑,我想得到一些指导。

自我回答,在评论的帮助下,我找到了原因:


调用类型名称后使用.self Postfix Self Expression:

A postfix self expression consists of an expression or the name of a type, immediately followed by .self. It has the following forms:

expression.self
type.self

The first form evaluates to the value of the expression. For example, x.self evaluates to x.

The second form evaluates to the value of the type. Use this form to access a type as a value. For example, because SomeClass.self evaluates to the SomeClass type itself, you can pass it to a function or method that accepts a type-level argument.

因此,需要 .self 关键字来将类型视为能够作为参数传递给函数的值。