3
  @IBAction func button(sender : AnyObject) {
    var videoConnection : AVCaptureConnection!
    videoConnection = nil
    var connection : AVCaptureConnection
    var port : AVCaptureInputPort
    var stillImageOutput : AVCaptureStillImageOutput?

    for connection in stillImageOutput?.connections{ //this line is where the error is

 }

}

I am trying to take a picture with my custom camera and I am getting this error

Jim
  • 33
  • 6

2 Answers2

10

stillImageOutput is an optional - even if you are using optional chaining, it cannot be used in a for loop, because if stillImageOutput is nil, the statement would be:

for connection in nil {
}

which wouldn't make sense.

To fix it, you have to use optional binding:

if let connections = x?.connections {
    for connection in connections {

    }
}
Antonio
  • 71,651
  • 11
  • 148
  • 165
  • @Antonio, thanks for the idea of substituting "nil" for the variable as a way to sanity check code that uses optionals! – rob5408 Nov 23 '14 at 00:19
0

Just complementing Antonio's answer, if you are 100% sure that in a specific part of the code your optional is not nil, you can just use the ! directly in your var, to avoid the if let check.

for connection in stillImageOutput!.connections {

}
Lucas Eduardo
  • 11,525
  • 5
  • 44
  • 49