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

Swift中compactMap闭包返回nil不兼容类型问题排查

问题原因与解决方案

你的代码报错是因为Swift没有正确推断出compactMap闭包的返回类型为可选型。虽然你在分支里返回了nil,但Swift优先根据闭包最后一行返回的BasicAttachmentInput实例,推断闭包的返回类型为非可选的BasicAttachmentInput,导致nil无法匹配该类型。

修复方法

明确指定闭包的返回类型为BasicAttachmentInput?,让Swift知道闭包可以返回可选值:

private func createSecondaryAttachments(
    _ attachments: [RegisteredMediaAttachment]
) -> [BasicAttachmentInput] {
    return attachments.compactMap { attachment -> BasicAttachmentInput? in
        guard let name = URL(string: attachment.registration.uploadUrl) else {
            return nil
        }

        return BasicAttachmentInput(
            name: name,
            contentType: attachment.attachment.type.mime(),
            sizeBytes: attachment.attachment.data.count,
            mediaId: attachment.registration.media.id
        )
    }
}

这样compactMap就能正确识别闭包返回的可选值,自动过滤掉nil项,编译就能通过了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 21:37:39