swift 尝试访问保存的数据,但出现错误

aurhwmvo  于 2023-09-29  发布在  Swift
关注(0)|答案(1)|浏览(94)

我试图访问一个变量,但即时通讯得到我的错误,这是我的代码
在我关闭我的设备之前,它一直在工作,但现在它给了我错误,有人知道我做错了什么吗?或者有什么建议?

import SwiftUI
import UIKit

struct ItemDetail: View {
    let item: MenuItem
    @State var Amount: Int = 1
    @State var amountCoice: String = "Servings"
    @State var Calories: Int = 0
    @State var ItemsInMeal: [String] = []
    @State var Price: Int = 0
    
   
    var body: some View {
            VStack{
            
            HStack(){
                TextField("weigth", value: $Amount, formatter: NumberFormatter())
            }
            Menu {
                Button {
                    self.amountCoice = "kcal"
                    print(self.amountCoice)
                }label: {
                    Text("kcal")
                }
                
                Button {
                    self.amountCoice = "Grams"
                    print(self.amountCoice)
                } label: {
                    Text("grams")
                }
                Button {
                    self.amountCoice = "Servings"
                    print(self.amountCoice)
                } label: {
                    Text("servings")
                }}label: {
                    Text("Choice amount")
                    Image(systemName: "chevron.up")
                }
                Image("\(item.thumbnailImage)@2x").clipShape(Circle())
                VStack(alignment: .leading){
                    Text(item.name)
                    Text("$\(item.price)")
                }
                Button{
                    self.ItemsInMeal.append(item.name)
                    UserDefaults.standard.set(ItemsInMeal, forKey: "ItemsInMeal")
                    Price += item.price 
                    UserDefaults.standard.set(Price, forKey: "Price")
                    print("\(self.ItemsInMeal), price: $\(self.Price)")
                } label: {
                    Text("add")
                }
             
            } 
            .onAppear(){
                self.ItemsInMeal = UserDefaults.standard.stringArray(forKey: "ItemsInMeal")! ///here’s where i get the error “An implicitly unwrapped optional was found here”///
                self.Price = UserDefaults.standard.integer(forKey: "Price")
                
            }
        }    
    }

我试过加一个??Self.ItemsInMeal = []但这不是发生的事情,我也尝试过使用!但它仍然给我一个错误错误一个隐式展开可选的地方,我设置ItemsInMeal保存的数据我是一个新的编码器,并没有线索,这意味着什么

cwtwac6a

cwtwac6a1#

如果ItemsInMeal尚未保存,UserDefaults将返回nil。你需要提供一个像这样的默认值:

self.ItemsInMeal = UserDefaults.standard.stringArray(forKey: "ItemsInMeal") ?? []

一般来说,最好避免用力拆包!

相关问题