A warning "'init()' is deprecated". [Swift, Ios app, learning model]

Viewed 2351

I am making a image classification iOS app with Swift.

When I write

guard let model = try? VNCoreMLModel(for: SqueezeNet().model) else { return }

I got this warning.

'init()' is deprecated: Use init(configuration:) instead and handle errors appropriately.

Do you know how to get rid of it?

3 Answers

As the message notes, init() is deprecated. The new initializer takes a configuration parameter. The default configuration may be fine for you, in which case you would replace SqueezeNet() with:

SqueezeNet(configuration: MLModelConfiguration())

For me the code of an Apple sample project worked out:

guard let mlModel = try? YOLOv3(configuration: .init()).model,
              let model = try? VNCoreMLModel(for: mlModel) else {
            print("Failed to load detector!")
            return


this was the code which gave me the warning:

guard let model = try? VNCoreMLModel(for: YOLOv3().model) else {
            print("Could not load model")
            return

That's odd. Right click SqueezeNet() and jump to it's definition. It will take you to the class.

Find the init() method of the class. It should look like this within your SqueezeNet class:

/**
    Construct SqueezeNet instance by automatically loading the model from the app's bundle.
*/
@available(*, deprecated, message: "Use init(configuration:) instead and handle errors appropriately.")
convenience init() {
    try! self.init(contentsOf: type(of:self).urlOfModelInThisBundle)
}

I'm not sure how you set up your ML, but it appears as though the:

  • @available(*, deprecated, message: "Use init(configuration:) instead and handle errors appropriately.")

Isn't passing for you. This could mean any of the following:

  1. You set up your ML incorrectly
  2. Your iOS isn't up to date

Easy Fix:

All you have to do is paste this into your project:

extension SqueezeNet {
    convenience init(_ foo: Void) {
        try! self.init(contentsOf: type(of:self).urlOfModelInThisBundle)
    }
}

Then, edit your code like this:

guard let model = try? VNCoreMLModel(for: SqueezeNet(()).model) else { return }

It should no work fine. Please let me know if it doesn't.

Related