swiftxcodeswiftuipreview

Why `#Preview(_:traits:_:body:)` is only available in iOS 17.0?


This question is not a Code question but I think it is related to the coding and programming and follows the StackOverflow guidelines.

I was using #Preview normally, but I needed to make the preview to fit to my view, so I did:

#Preview(traits: .sizeThatFitsLayout)

But I got:

🛑 'Preview(:traits::body:)' is only available in iOS 17.0 or newer

As an apple engineer suggested, I see I can use PreviewProvider to make it available for iOS 13 which is my target OS.

But this raises a couple of questions:

  1. Isn't #Preview just another implementation of the PreviewProvider under the hood? 1.1 If yse, so why it's not supporting older version. 1.2 If no, why? Is there any issues with the original PreviewProvider?

  2. Isn't Preview for Xcode? So why is it not running? Is Xcode depends on the iOS some how?


Solution

  • Your question is a code question. You are asking about a SwiftUI macro named Preview (See Previews in Xcode). Like any Swift API, the API was added at specific versions of the various OSes.

    The older Preview(_:body:) was added as of iOS 13.0/macOS 10.15. But the newer Preview(_:traits:_:body:) was added as of iOS 17.0/macOS 14.0. As you have seen, if your target's Base SDK is older than those, you get a warning such as:

    'Preview(:traits::body:)' is only available in iOS 17.0 or newer

    So while the Preview macro is being used by Xcode, it is still code written with Swift APIs and those APIs require a specific OS version for their availability.