【译】The different types of self in Swift

265 阅读1分钟

原文: The different types of self in Swift

Swift 中各种各样的self

作为我上一篇文章的简短后续,我认为列举Swift中各种类型的self会有所帮助。这是一个可以表达很多意思的术语,正因如此,经常让人感到困惑。

前缀 self.

"前缀 self",或者说self.,是最主要,最基础的self——是我们最熟悉的那个self.在别的编程语言中,一般称其为this,指向封闭类型的实例。当指向封闭类型的成员时,我们显式或隐式地使用self.

Example:

struct Person {
	let name: String
    
    init(name: String) {
    	self.name = name
    }
}

后缀 .self

后缀.self,指代的是被调用的类型的元类型。

Swift Programming Language Book 上是这样描述的:

You can use the postfix self expression to access a type as a value. For example, SomeClass.self return SomeClass itself, not an instance of SomeClass. And SomeProtocol.self returns SomeProtocol itself, not an instance of a type that conforms to SomeProtocol at runtime.

Example:

class SomeClass {}
SomeClass.self

译者:.self可以用在类型后面取得类型本身,也可以用在实例后面取得这个实例本身

大写Self

大写的Self其实根本不是一个类型,而是运行时特定类型的“占位符”

Swift Programming Language Book 上是这样描述的:

The Self type isn't a specific type, but rather lets you conveniently refer to the current type without repeating or knowing that type's name.

In a protocol declaration or a protocol member declaration, the Self type refers to the eventual type that conforms to the protocol.

译者: Self不仅指代的是实现该协议的类型本身,也包括了这个类型的子类

Example:

extension FloatingPoint {
	static var one: Self {
    	Self(1)
    }
}

// usage
Double.one
Float.one
CGFloat.one