Swift:具有共同初始化部分的多个初始化程序

时间:2017-05-02 05:55:46

标签: swift

我有class Node

class Node {
  let name:String
  let device: MTLDevice
  let vertexBuffer: MTLBuffer

  init(name: String, device: MTLDevice, vertices: Array<Float>){
    self.name=name
    self.device=device
    self.vertexBuffer=toVertexBuffer(vertices)
  }
  init(name: String, device: MTLDevice, vertices: UnsafeMutablePointer<GLfloat>, count: Int){
    self.name=name
    self.device=device
    self.vertexBuffer=toVertexBuffer(vertices, count)
  }
}

我想规范化我的课程初始化。我想将namedevice成员的初始化移到单独的函数或初始化中,以避免代码冗余。有点像

class Node {
  let name:String
  let device: MTLDevice
  let vertexBuffer: MTLBuffer

  init(name: String, device: MTLDevice, vertices: Array<Float>){
    self.init(name:name, device:device)
    self.vertexBuffer=toVertexBuffer(vertices)
  }
  init(name: String, device: MTLDevice, vertices: UnsafeMutablePointer<GLfloat>, count: Int){
    self.init(name:name, device:device)
    self.vertexBuffer=toVertexBuffer(vertices, count)
  }
  private init(name: String, device: MTLDevice){
    self.name=name
    self.device=device
  }
}

我知道上面的代码有些错误。怎么做正确的方法?

2 个答案:

答案 0 :(得分:2)

你走在正确的轨道上。创建一个私有的指定初始化程序(如果您不希望直接调用它)并为需要转换的值添加便利初始化程序(请参阅Designated Initializers and Convenience Initializers

class Node {
    let name: String
    let device: MTLDevice
    let vertexBuffer: MTLBuffer

    private init(name: String, device: MTLDevice, buffer: MTLBuffer) {
        self.name = name
        self.device = device
        self.vertexBuffer = buffer
    }

    convenience init(name: String, device: MTLDevice, vertices: Array<Float>) {
        self.init(name: name, device: device, buffer: toVertexBuffer(vertices))
    }

    convenience init(name: String, device: MTLDevice, vertices: UnsafeMutablePointer<GLfloat>, count: Int) {
        self.init(name: name, device: device, buffer: toVertexBuffer(vertices, count))
    }
}

答案 1 :(得分:0)

这应该是有效的。你需要一个指定的初始化程序,然后其他初始化程序只需要调用它。

class Node {
let name: String
let device: MTLDevice
let vertexBuffer: MTLBuffer


init(name: String, device: MTLDevice, vertices: UnsafeMutablePointer<GLfloat>, count: Int){
    self.name = name
    self.device = device
    self.vertexBuffer = MTLBuffer()
}
convenience init(name: String, device: MTLDevice, vertices: UnsafeMutablePointer<GLfloat>){
    self.init(name: name, device: device, vertices: vertices, count: 0)
}

}