我对Swift语言中的“元类型”概念感到非常困惑。

假设我有:

class SomeClass {
    class func callClassMethod() {
        print("I'm a class method. I belong to my type.")
    }

    func callInstanceMethod() {
        print("I'm an instance method. I belong to my type instance.")
    }
}


根据定义:


  元类型类型是指任何类型的类型,包括类类型,
  结构类型,枚举类型和协议类型。


SomeClass已经是一种称为SomeClass的类型,那么SomeClass的类型到底是什么?

我可以创建SomeClass.Type变量:

let var1 : SomeClass.Type = SomeClass.self
var1.doIt();//"I'm a class method. I belong to my type."


但是我也可以这样调用static / class函数:

SomeClass.doIt();//"I'm a class method. I belong to my type."


他们是一样的吗?

最佳答案

它们是相同的,因为编译器保证类名是唯一的(Swift是按模块隔开的名称),因此只有一个是SomeClass.Type的,也就是类SomeClass。当您只想将某物的类型传递给函数但又不想传递实例时,元类型通常很有用。 Codable例如这样做:

let decoded = try decoder.decode(SomeType.self, from: data)


如果您不能在此处传递元类型,则编译器仍可以基于左侧的注释来推断返回类型,但可读性较差:

let decoded: Sometype = try decoder.decode(data)


尽管Apple偏爱使用元类型作为其更清晰的含义,但某些库的确使用类型推断样式,而不依赖于左侧的类型推断。

关于swift - Swift中的元类型到底是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58982598/

10-12 14:34
查看更多