Swift Error Message When Instantiating Object – Solution | Hacking Swift 5.5, Xcode 13, and iOS 15

https://youtu.be/8Gl33PpOlJg

How to Instantiate an Object Properly in Swift 5.5

by Alexandra Kropova from Mammoth Interactive

Are you getting a warning or error message when instantiating a new object in Swift? Read the solution in this post.

Want to learn more? Enroll in Complete Web & App Development with Machine Learning For All (125 Hours). Free in the Mammoth Unlimited Membership. Get 250+ courses and 2,000 hours at a dirt-cheap price.

YouTubeTwitter | Github


An example where the problem occurs:

let model = MobileNetV2()

Error message:

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

Solution

You must wrap the instantiation into a do catch statement, in case the instantiation fails. Use the following Swift 5.5 code:

let model: MobileNetV2 = {
        
        do {
            
            let config = MLModelConfiguration()
            return try MobileNetV2(configuration: config)
            
        } catch {
            
            print(error)
            fatalError("Couldn't create MobileNetV2")
            
        }
    }()

Toolkit:

  • Xcode 13
  • Swift 5.5
  • SwiftUI 3
  • iOS 15
  • CoreML

 

Suggest more solutions or ask a question in the comments below.

Want to learn more? Enroll in Complete Web & App Development with Machine Learning For All (125 Hours). Free in the Mammoth Unlimited Membership. Get 250+ courses and 2,000 hours at a dirt-cheap price.

YouTubeTwitter | Github

 


I am: *

 

You authorize us to send you information about our products.

 I would like to receive the Mammoth Interactive newsletter

 

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp’s privacy practices here.

Mammoth Interactive Favicon

Why you NEED to take this course :

Get in Touch.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

EMAIL US

support@mammothinteractive.com