let renderEncoderOpt = commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor)

if let renderEncoder = renderEncoderOpt {
  renderEncoder.setRenderPipelineState(pipelineState)
  renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, atIndex: 0)
  renderEncoder.drawPrimitives(.Triangle, vertexStart: 0, vertexCount: 3, instanceCount: 1)
  renderEncoder.endEncoding()
}

上面的代码抛出一个
 Initializer for conditional binding must have Optional type, not 'MTLRenderCommandEncoder'

如果我尝试使renderencoderopt成为可选的,问题仍然存在。我试过用Guard Let vs if Let进行测试,并尝试将其设置为optionals和redeclaring type等,但它一直回到这个问题上。这在SWIFT 1/1.2中运行良好
有人有指针吗?

最佳答案

renderCommandEncoderWithDescriptor没有返回可选的,因此您应该完全删除if let条件绑定,直接使用结果。

let renderEncoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor)

renderEncoder.setRenderPipelineState(pipelineState)
renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, atIndex: 0)
renderEncoder.drawPrimitives(.Triangle, vertexStart: 0, vertexCount: 3, instanceCount: 1)
renderEncoder.endEncoding()

10-06 04:12