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

iOS开发:如何条件构建AppShortcuts列表?解决buildOptional错误

解决App Shortcuts条件构建的编译错误

错误原因

@AppShortcutsBuilder的闭包语法糖不支持直接在内部使用if #available条件分支,其构建器逻辑在处理可选元素时会产生类型歧义,导致Ambiguous use of 'buildOptional'编译错误。

解决方案

绕过@AppShortcutsBuilder的语法限制,直接手动构建AppShortcut数组,通过条件判断实现分版本添加快捷方式:

实现代码

@available(iOS 16.0, *)
struct CJAppShortcutsList: AppShortcutsProvider {
    
    static var appShortcuts: [AppShortcut] {
        // 基础快捷方式(iOS16.0+通用)
        var shortcuts = [
            AppShortcut(
                intent: CJAddContact(),
                phrases: [
                    "Add Contact to \(.applicationName)",
                    "Create Contact in \(.applicationName)",
                ],
                shortTitle: "Create New Contact",
                systemImageName: "person.crop.circle.fill.badge.plus"
            )
        ]
        
        // iOS16.4+专属快捷方式
        if #available(iOS 16.4, *) {
            shortcuts.append(
                AppShortcut(intent: CJOpenContactIntent(),
                            phrases: ["Open Contact in \(.applicationName)", "Show Contact in \(.applicationName)"],
                            shortTitle: "Open Contact",
                            systemImageName: "person.crop.circle")
            )
        }
        
        return shortcuts
    }
}

额外注意事项

由于CJOpenContactIntent依赖iOS16.4的ForegroundContinuableIntentAPI,需要给该Intent添加版本限制:

@available(iOS 16.4, *)
struct CJOpenContactIntent: ForegroundContinuableIntent {
    // 你的Intent逻辑实现
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:33:19