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.
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.