ios - .self 在 Swift 中的结构类型之后

标签 ios objective-c swift reflection metaclass

我对 Metal 示例中的一行代码感到困惑,其中内存指针绑定(bind)到一个类型。

uniforms = UnsafeMutableRawPointer(uniformBuffer.contents()).bindMemory(to: Uniforms.self, capacity: 1)

我的困惑是Uniforms 类型之后的.selfUniforms 是在 Objective-C 文件中定义的结构,如果调用中没有 .self,代码将无法运行。为什么有必要?

最佳答案

.self 返回相应类型的元类型实例。将其视为类型安全的类型标识符(例如,比使用字符串更安全)。然后,您可以在此类元类型实例上安全地调用可用的初始化程序、静态方法和静态属性。

例如,您也可以将它存储在一个变量中:

let metatype: Uniforms.Type = Uniforms.self

Uniforms.Type实际元类型(即类型的类型)。

元类型速成类。一个非常简单的示例,可以让您了解这些元数据实际上有何用处:

class Super {
    let id: Int
    required init(id: Int) { self.id = id }
}

class SubA: Super { ... }
class SubB: Super { ... }

let subclass: Super.Type = SubA.self

然后,稍后,使用 subclass 创建一个实例,没有对实际子类类型名称进行硬编码:

let obj = subclass.init(id: 123) // new SubA instance.

关于ios - .self 在 Swift 中的结构类型之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47255908/

相关文章:

iphone - 在 iOS4.3 和 iOS 5 的 phonegap 中暂停和恢复听众不工作

ios - 识别 UITableViewCell 中的 UIButton 不起作用 - Swift

ios - NSAttributedString 中字距调整的不一致行为

swift - 代表 RealmSwift 中的范围值?

ios - Mapkit 标注附件按钮激活

ios - 如何在不放大 View 的情况下缩放 View ?

ios - 你如何真正从 UIMenuController 中删除 Copy

ios - 如何处理 UIDeviceOrientationFaceUp 和 UIDeviceOrientationFaceDown?

iOS 加载 xib 给出 setValue :forUndefinedKey:]

ios - 通缉解释 : Concept of passing data between UIViewController and UIView