gpt4 book ai didi

ios - 在 swift 中开设一个类中的类的成本是多少?

转载 作者:行者123 更新时间:2023-11-30 11:54:35 26 4
gpt4 key购买 nike

我正在尝试在类中快速创建类,以便我可以更轻松地按类别访问变量。例如,我的渲染器有很多管道,因此能够转到 pipelines.<whateverPipelineINeed> 可能会很好。或者我的构建器可能有各种可以构建的管道,所以我可能想要 Builder.pipelines.<whatEverPipelineINeed>()

这促使我生成如下所示的代码

class Renderer: NSObject, MTKViewDelegate {
let device:MTLDevice!
let queue:MTLCommandQueue!
let depth:MTLDepthStencilState!

class Pipelines {
static var defaultTriangles:MTLRenderPipelineState!
static var fancyTriangles:MTLRenderPipelineState!
}
.......
}

class Builder {
class func loadTexture(device: MTLDevice,
textureName: String) -> MTLTexture? {
...
}

class PipelineStates {
class func blankTriangle(device: MTLDevice) -> MTLRenderPipelineState? {
...
}

class func fancyTriangle(device: MTLDevice) -> MTLRenderPipelineState? {
...
}
}
}

当然,这些管道远不止 2 个,我正在将这种模式用于其他对象。此外,不存在 = builder.() 的模式,因为某些对象经常初始化。此外,我还会使用可选类型检查编译中的错误。

这是一种快速做事的好方法吗?我应该了解与执行此类操作相关的低效率成本吗?

此外还有更好的方法吗?

最佳答案

你可以将它包装成枚举

public enum Pipeline {

public enum PipelineName: String {
case defaultTriangles
case fancyTriangles
}

case defaultTriangles(MTLRenderPipelineState)
case fancyTriangles(MTLRenderPipelineState)

public var pipelineState: MTLRenderPipelineState {
switch self {
case .defaultTriangles(let pipeline): return pipeline
case .fancyTriangles(let pipeline): return pipeline
}
}

public init?(withDevice device: MTLDevice,
library: MTLLibrary,
pipelineName: PipelineName) {
switch pipelineName {
case .defaultTriangles:
let pipelineDescriptor = MTLRenderPipelineDescriptor()
// Set descriptor properties
guard
let pipelineState = try? device.makeRenderPipelineState(descriptor: pipelineDescriptor)
else {
return
}
self = .defaultTriangles(pipelineState)
case .fancyTriangles:
let pipelineDescriptor = MTLRenderPipelineDescriptor()
// Set descriptor properties
guard
let pipelineState = try? device.makeRenderPipelineState(descriptor: pipelineDescriptor)
else {
return
}
self = .defaultTriangles(pipelineState)
}
}

}

然后像这样初始化:

guard 
let pipeline = Pipeline(withDevice: device,
library: library,
pipelineName: .defaultTriangles)
else { return }
self.defaultPipeline = pipeline

然后当您需要渲染访问管道时,如下所示:

self.defaultPipeline.pipeline
/// Execute commands and set arguments / etc.

另外,使用中缀运算符定义渲染 channel 也很酷:

defaultTriangles |--> triangleComputationPipeline |--> fancyTriangles

关于ios - 在 swift 中开设一个类中的类的成本是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47964795/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com