Search code examples
swiftmacosswiftuideprecateddeprecation-warning

Can I use a deprecated function (method) in SwiftUI?


I'm developing a macOS app using Xcode 14.0 with Swift 5.7 and SwiftUI. I'm running macOS 12.6 on my MacBook M1 Pro. I need to support at minimum macOS 11.0 which means that there are many new SwiftUI functions I cannot use due to them needing macOS 12.0+. One function that I use quite a bit for SwiftUI layout is overlay(_:alignment:). According to the Apple document, it's deprecated. It's interesting because I'm still able to use it in my code with the setup I described. However, is this going to break the app when deployed if the function is technically deprecated? Apple isn't exactly great with backward compatibility in general and it's also very hard to find out the information about backward compatibility until your app just breaks or gets rejected from the App Store. As mentioned earlier, I can't use the suggested overlay(alignment:content:) because it needs macOS 12.0+.

Maybe I should just drop macOS 11 and require macOS 12 since it's been several years now, but from what I read a lot of users (>70%) are still running macOS 11 based on a survey conducted in 2021. Maybe that's different now that macOS 13 is already out.

enter image description here


Solution

  • It's safe to keep using the deprecated version of overlay. Apple won't remove it from SwiftUI for years, if ever.

    But if you want to be extra safe, you can write your own modifier that uses the deprecated overlay if the new overlay is not available:

    extension View {
        @ViewBuilder
        func overlayWorkaround<V: View>(
            alignment: Alignment = .center,
            @ViewBuilder _ content: () -> V
        ) -> some View {
            if #available(macOS 12, macCatalyst 15, iOS 15, tvOS 15, watchOS 8, *) {
                self.overlay(alignment: alignment, content: content)
            } else {
                self.overlay(content(), alignment: alignment)
            }
        }
    }