You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift包兼容Xcode15/16:如何针对@Previewable宏做条件编译?

兼容Xcode 15和16的SwiftUI预览内联@State解决方案

要同时适配Xcode 15和16,解决内联@State的警告与编译冲突问题,可以通过Xcode版本条件编译来区分处理@Previewable宏的使用:

核心思路

@Previewable是Xcode 16(对应Swift 5.10)新增的宏,Xcode 15及更早版本并不支持。因此我们可以通过检查Xcode的版本号,在不同环境下生成对应的代码:

完整代码示例

@available(iOS 17.0, *)
struct ColorPickerView: View {
    @Binding var selectedColor: Color
    
    var body: some View {
        selectedColor
    }
}

@available(iOS 17.0, *)
#Preview {
    #if Xcode >= 1600
    @Previewable @State var selectedColor = Color.blue
    #else
    @State var selectedColor = Color.blue
    #endif
    
    return ColorPickerView(selectedColor: $selectedColor)
}

替代方案:基于Swift版本判断

也可以通过Swift版本来做条件判断(Xcode 16对应Swift 5.10,Xcode 15对应Swift 5.9):

@available(iOS 17.0, *)
#Preview {
    #if swift(>=5.10)
    @Previewable @State var selectedColor = Color.blue
    #else
    @State var selectedColor = Color.blue
    #endif
    
    return ColorPickerView(selectedColor: $selectedColor)
}

说明

  • 使用Xcode版本判断(Xcode >= 1600)更直接,因为@Previewable是Xcode工具链引入的特性,和Xcode版本强绑定。
  • 两种方式都能实现:在Xcode 16中自动添加@Previewable消除警告,在Xcode 15中使用原有代码正常编译。

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 08:20:06