Swift 2 call can throw, but is not marked with try

Updated my code to Swift 2 and am getting a "Call can throw, but it is not marked with 'try' and the error is not handled" error in a variable declaration and I'm not sure how to fix it. The code in question is this:


let input   : AVCaptureDeviceInput? = AVCaptureDeviceInput(device: device) as? AVCaptureDeviceInput

Accepted Reply

Error Handling is one of the biggest changes in Swift 2.0 and you should learn it before migrating to Swift 2.0 .


The initializer is imported as: (see - initWithDevice:error: in AVCaptureDeviceInput)

init(device device: AVCaptureDevice!) throws

You need two things when using `throws` method or initializer.

- enclose it with do-catch block

- prefix `try`

So, your code needs to be changed to something like this:

let input   : AVCaptureDeviceInput?
do {
    input = try AVCaptureDeviceInput(device: device)
} catch _ {
    //Error handling, if needed
}

(Swift migrator does these changes automatically. Why don't you use it?)

Replies

do {
    let input = try AVCaptureDeviceInput(device: device)

     // use input
} catch {
    fatalError("Could not create capture device input.")
}

Error Handling is one of the biggest changes in Swift 2.0 and you should learn it before migrating to Swift 2.0 .


The initializer is imported as: (see - initWithDevice:error: in AVCaptureDeviceInput)

init(device device: AVCaptureDevice!) throws

You need two things when using `throws` method or initializer.

- enclose it with do-catch block

- prefix `try`

So, your code needs to be changed to something like this:

let input   : AVCaptureDeviceInput?
do {
    input = try AVCaptureDeviceInput(device: device)
} catch _ {
    //Error handling, if needed
}

(Swift migrator does these changes automatically. Why don't you use it?)

Thanks, that works and the explanation helped. I did use the swift migrator but for whatever reason it didn't touch this part of the code.

I did use the swift migrator but for whatever reason it didn't touch this part of the code.

I see. I have experienced the similar issues. But if you traced the parts the migrator converted, you might have found how error handling code should be.

(In fact, when there were not much info about new Swift 2 features. I learned how to migrate my codes from the Swift migrator.)


Anyway, you may need some more steps to make your code work with Swift2/new SDKs. Hoping your app works well soon.