iOS 15下WidgetConfiguration添加systemExtraLarge报错如何解决
问题原因
- 错误Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type触发原因:
你的body属性声明为返回some WidgetConfiguration不透明类型,在未添加@ViewBuilder修饰符的场景下,多分支判断代码无法隐式返回每个分支的执行结果,编译器无法推导统一的返回值类型,因此抛出该错误。 - 警告Result of call to 'supportedFamilies' is unused触发原因:
因为没有指定返回值,两个分支中IntentConfiguration链式调用的结果被当成普通临时变量处理,没有被作为body的返回值使用,因此编译器提示返回结果未被使用。
修复方案
方案1(无冗余代码,最推荐)
仅动态构造支持的尺寸数组即可,无需重复编写完整的IntentConfiguration代码:
var body: some WidgetConfiguration { let supportedFamilies: [WidgetFamily] if #available(iOSApplicationExtension 15.0, *) { supportedFamilies = [.systemSmall, .systemMedium, .systemLarge, .systemExtraLarge] } else { supportedFamilies = [.systemSmall, .systemMedium, .systemLarge] } return IntentConfiguration( kind: "Widget", intent: SelectProjectIntent.self, provider: Provider() ) { entry in ProgressWidgetEntryView(entry: entry) } .configurationDisplayName("Title") .description("Description") .supportedFamilies(supportedFamilies) }
方案2(保留原分支写法)
给body属性添加@ViewBuilder修饰符,让SwiftUI的Builder语法可以正确解析多分支返回值:
@ViewBuilder var body: some WidgetConfiguration { if #available(iOSApplicationExtension 15.0, *) { IntentConfiguration( kind: "Widget", intent: SelectProjectIntent.self, provider: Provider() ) { entry in ProgressWidgetEntryView(entry: entry) } .configurationDisplayName("Title") .description("Description") .supportedFamilies([.systemSmall, .systemMedium, .systemLarge, .systemExtraLarge]) } else { IntentConfiguration( kind: "Widget", intent: SelectProjectIntent.self, provider: Provider() ) { entry in ProgressWidgetEntryView(entry: entry) } .configurationDisplayName("Title") .description("Description") .supportedFamilies([.systemSmall, .systemMedium, .systemLarge]) } }
也可以选择不添加@ViewBuilder修饰符,直接在每个分支的IntentConfiguration前加return关键字即可解决报错。
内容的提问来源于stack exchange,提问作者Tomeu Mascó
相关产品推荐
相关产品推荐

