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

如何在新版AppShortcutsProvider的@AppShortcutsBuilder中为AppShortcut设默认值?

问题解决思路
  • 问题核心:AppShortcut初始化时手动传递的默认参数不会被AppIntents框架正确绑定到运行时的Intent实例,框架优先依赖Intent类本身定义的参数默认值。

  • 修正步骤:

    1. 确保ExecuteAction Intent类中,action参数通过@Parameter的defaultValue定义默认值,而非仅在初始化时传递:
      struct ExecuteAction: AppIntent {
          static var title: LocalizedStringResource = "执行动作"
          
          @Parameter(title: "动作", defaultValue: .startTimer)
          var action: ActionType
          
          func perform() async throws -> some IntentResult {
              // 此处action将不再为nil
              return .result()
          }
      }
      
    2. 修改AppShortcuts初始化代码,不再手动传递action参数,让Intent自动使用自身定义的默认值:
      @AppShortcutsBuilder static var appShortcuts: [AppShortcut] {
          AppShortcut(intent: ExecuteAction(), phrases: [
              "Start working time with \(.applicationName)",
          ])
      }
      
    3. 确认ActionType枚举符合AppIntents要求,比如实现CaseIterable、Identifiable(若需本地化展示还需配置对应描述):
      enum ActionType: String, AppEnum, CaseIterable, Identifiable {
          case startTimer
          case stopTimer
          
          var id: String { rawValue }
          
          static var typeDisplayName: LocalizedStringResource = "动作类型"
          static var caseDisplayNames: [Self: LocalizedStringResource] = [
              .startTimer: "开始计时",
              .stopTimer: "停止计时"
          ]
      }
      

调整后,action参数会正确获取默认值,不会再出现nil的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 14:01:26