2
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()
}

The code above throws an

 Initializer for conditional binding must have Optional type, not 'MTLRenderCommandEncoder'

If i try and make renderEncoderOpt an optional though, the issue still remains. I've tried testing with guard let vs if let, and tried setting it to optionals, and redeclaring type etc, but it keeps coming back to this issue. This worked ok in swift 1/1.2

Does anyone have an pointers?

stktrc
  • 1,599
  • 18
  • 30
  • I would suspect that the right hand side of top line (= commandBuffer...) is not an optional. See http://stackoverflow.com/questions/31038759/if-let-error-initializer-for-conditional-binding-must-have-optional-type-not – dfrib Dec 07 '15 at 00:11

3 Answers3

2

The renderCommandEncoderWithDescriptor is not returning an optional, so you should remove the if let conditional binding altogether and just use result directly.

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()
Rob
  • 415,655
  • 72
  • 787
  • 1,044
0

Rob answered this question in the comments. You can't use the if let syntax if the object isn't optional. This error is telling you that.

Daniel T.
  • 32,821
  • 6
  • 50
  • 72
0

The function renderCommandEncoderWithDescriptor is defined as follows

func renderCommandEncoderWithDescriptor(_ renderPassDescriptor: MTLRenderPassDescriptor) -> MTLRenderCommandEncoder

(source: https://developer.apple.com/library/prerelease/ios/documentation/Metal/Reference/MTLCommandBuffer_Ref/index.html#//apple_ref/occ/intfm/MTLCommandBuffer/renderCommandEncoderWithDescriptor:)

The return type MTLRenderCommandEncoder is a graphics rendering command encoder object, which is a non-optional object. (source: https://developer.apple.com/library/prerelease/ios/documentation/Metal/Reference/MTLRenderCommandEncoder_Ref/index.html#//apple_ref/swift/intf/c:objc(pl)MTLRenderCommandEncoder)

Hence, your if let conditional binding

if let renderEncoder = renderEncoderOpt {

fails. Simply remove this if statement and your code should work.

dfrib
  • 70,367
  • 12
  • 127
  • 192