我有 2 個自定義單選按鈕。當我單擊其中一個時,我希望它們保存到核心資料變數,但出現此錯誤。" 無法賦值:'selected' 是一個 'let' 常量"
這就是我呼叫單選按鈕的方式:
RadioButtonGroups { selected in // <- Error here
print("Selected payment is: \(selected)")
selected = coreDataViewModel.savedCart[0].paymentMethod
coreDataViewModel.manager.save()
}
這是我的單選按鈕結構:
struct RadioButtonField: View {
let id: String
let label: String
let size: CGFloat
let img : String
let color: Color
let textSize: CGFloat
let isMarked:Bool
var callback: (String)->()
init(
id: String,
label:String,
img : String,
size: CGFloat = 20,
color: Color = Color.colorGrayDark,
textSize: CGFloat = 16,
isMarked: Bool = false,
callback: @escaping (String)->()
) {
self.id = id
self.label = label
self.size = size
self.color = color
self.textSize = textSize
self.isMarked = isMarked
self.callback = callback
self.img = img
}
var body: some View {
Button(action:{
self.callback(self.id)
}) {
HStack(alignment: .center, spacing: 10) {
Image(img, bundle: Bundle.main)
Text(label)
.font(Font.system(size: textSize))
Spacer()
Image(self.isMarked ? "checkboxSelected" : "checkboxUnselected")
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: self.size, height: self.size)
// Spacer()
}.foregroundColor(self.color)
}
.foregroundColor(Color.white)
}
}
struct RadioButtonGroups: View {
var callback: (String) -> ()
@State var selectedId: String = ""
var body: some View {
VStack {
radioCash
radioCard
}
}
var radioCash: some View {
RadioButtonField(
id: Payment.cash.rawValue,
label: Payment.cash.rawValue, img: "cash",
isMarked: selectedId == Payment.cash.rawValue ? true : false,
callback: radioGroupCallback
)
}
var radioCard: some View {
RadioButtonField(
id: Payment.card.rawValue,
label: Payment.card.rawValue, img: "card",
isMarked: selectedId == Payment.card.rawValue ? true : false,
callback: radioGroupCallback
)
}
func radioGroupCallback(id: String) {
selectedId = id
callback(id)
}
}
enum Payment: String {
case cash = "Cash"
case card = "Card (la livrare)"
}
我該如何解決這個問題?其次,這是將資料存盤到核心資料的好方法嗎?謝謝 !
uj5u.com熱心網友回復:
selected = coreDataViewModel.savedCart[0].paymentMethod
正在嘗試將模型中的值分配給selected,這是一個常數。不應該是
coreDataViewModel.savedCart[0].paymentMethod = selected
關于你的第二個問題,根據你提供的資訊,很難說。我建議的一件事是使用帶有字串原始值的列舉來處理諸如付款方式之類的事情,并在您的托管物件模型上計算屬性來訪問它們,這樣您就不會傳遞字串:
var paymentMethod: PaymentMethod {
get { PaymentMethod(rawValue: rawPaymentMethod) ?? .turnips }
set { rawPaymentMethod = newValue.rawValue }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381137.html
