Friday, August 19, 2022
HomeiOS Developmentios - Options for utilizing saved properties whose information kind is unavailable...

ios – Options for utilizing saved properties whose information kind is unavailable in your deployment goal

In Xcode variations up till 14 (Swift variations as much as 5.7), it was doable to make use of a lazy var to create a saved property whose information kind is unavailable in your deployment goal. For instance, RelativeDateTimeFormatter is new in iOS 13 so in case you needed to make use of it in an app that targets iOS 12, you would have outlined the next:

@accessible(iOS 13.0, *)
personal lazy var relativeDateTimeFormatter: RelativeDateTimeFormatter = {
    let formatter = RelativeDateTimeFormatter()
    formatter.dateTimeStyle = .numeric
    formatter.unitsStyle = .brief
    formatter.formattingContext = .standalone
    return formatter

And also you’d wrap that decision in if #accessible to make use of a distinct date formatter on iOS variations lower than 13. Because it’s costly to create date formatters, it is essential this be created solely as soon as and reused as you populate cells for instance. The saved property labored effectively for this, or so we thought. Now you get a compile-time error:

Saved properties can’t be marked doubtlessly unavailable with ‘@accessible’

The Xcode 14 launch notes state:

Saved properties in Swift can’t have kind info that’s doubtlessly unavailable at runtime. Nevertheless, previous to Swift 5.7 the compiler incorrectly accepted @accessible attributes on saved properties when the property had both the lazy modifier or an hooked up property wrapper. This might result in crashes for apps working on older working techniques. The Swift compiler now constantly rejects @accessible on all saved properties.

This brings us to the query: what options are there to implement this now?

An analogous situation to contemplate: say you need to add Reside Textual content help to a view controller in your app. To do that, you create an ImageAnalyzer and retailer it as a property on the view controller. The issue is that this API is new in iOS 16, so how do you add this so you should use it on iOS 16 whereas nonetheless sustaining help for older OS variations? This is not going to work:

@accessible(iOS 16.0, *)
personal(set) lazy var analyzer = ImageAnalyzer()



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments