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

Shopify iOS Buy SDK可选参数传nil报错的优雅解决方法问询

解决Shopify iOS Buy SDK可选字段传入Nil导致API失败的问题

问题核心:Shopify API对可选字段的处理逻辑是完全省略字段而非传入null,但直接给SDK的.value(:)传nil会生成null字段,触发API报错。以下是两种优雅的通用解决方案:

方案1:通用Input可选值转换扩展

为Storefront.Input添加便捷方法,自动将可选值转为对应枚举(有值时用.value,无值时用.undefined,后者会让SDK不在请求中包含该字段):

extension Storefront.Input {
    static func optional<T>(_ value: T?) -> Storefront.Input<T> {
        guard let value = value else {
            return .undefined
        }
        return .value(value)
    }
}

使用示例

创建CheckoutCreateInput时直接传入可选值即可:

let checkoutInput = Storefront.CheckoutCreateInput.create(
    email: .optional(email), // email为nil时自动省略该字段
    lineItems: .value(lineItemInput),
    note: .optional(note),
    allowPartialAddresses: .value(true)
)

对于多可选字段的MailingAddressInput同样适用:

let addressInput = Storefront.MailingAddressInput.create(
    address1: .optional(address1),
    address2: .optional(address2),
    city: .optional(city),
    province: .optional(province),
    country: .value(country),
    zip: .optional(zip)
)

方案2:扩展Input的Create方法(可选)

如果希望更贴近原生调用习惯,可以扩展目标Input类型的create方法,给可选参数设置默认值.undefined:

extension Storefront.CheckoutCreateInput {
    static func create(
        lineItems: Storefront.Input<[Storefront.CheckoutLineItemInput]>,
        email: Storefront.Input<String> = .undefined,
        note: Storefront.Input<String> = .undefined,
        allowPartialAddresses: Storefront.Input<Bool> = .undefined
    ) -> Self {
        return Storefront.CheckoutCreateInput.create(
            email: email,
            lineItems: lineItems,
            note: note,
            allowPartialAddresses: allowPartialAddresses
        )
    }
}

使用示例

只传入必填字段,可选字段按需传入:

let checkoutInput = Storefront.CheckoutCreateInput.create(
    lineItems: .value(lineItemInput),
    email: email.map(Storefront.Input.value) ?? .undefined,
    allowPartialAddresses: .value(true)
)

说明:方案1的通用性更强,无需为每个Input类型单独扩展,推荐优先使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 17:07:08