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

Swift中Data类型默认值是什么?PhotosPicker存CoreData遇问题

问题:将PhotosPicker图片存入CoreData的Data类型默认值困惑

我想把PhotosPicker选择的图片保存到CoreData(字段设为开启外部存储的二进制数据类型),但卡在了Data类型的默认值上——其他类型都能处理,唯独Data类型完全搞不清该用什么默认值。

原始代码如下:

import SwiftUI

struct ContentView: View {
    @State var value: Double = 0
    @State var title: String = ""
    @State var image: Data? = nil

    var body: some View {
        Button("Add", action: {
            Persistence.shared.add(value: value, title: title, image: image ?? /* 这里该填什么 */, context: viewContext)
        })
    }
}

后来搞明白,Data类型的默认值可以用Data(),CoreData存储空的Data实例几乎不占空间,而且它不是nil,刚好符合非可选的字段要求。修改后的代码如下:

Persistence.shared.add(value: value, title: title, image: image ?? Data(), context: viewContext)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 09:04:59