Swift 如何将@AppStorage用于字符串字典[String:String]

Swift 如何将@AppStorage用于字符串字典[String:String],swift,xcode,swiftui,appstorage,Swift,Xcode,Swiftui,Appstorage,嘿,在我的应用程序中,我试图存储用户是否希望某个位置成为其最喜爱的位置。为了在这个UserDefaults更新视图中进行更改,我需要使用@AppStorage。然而,目前我只得到错误“调用初始值设定项时没有精确匹配”我是否需要使用数据而不是[String:String],如果是,如何使用?有人知道如何解决这个问题吗?提前谢谢 import SwiftUI struct SpotDetailView: View { @State var spot: WindApp //knows whi

嘿,在我的应用程序中,我试图存储用户是否希望某个位置成为其最喜爱的位置。为了在这个UserDefaults更新视图中进行更改,我需要使用@AppStorage。然而,目前我只得到错误“调用初始值设定项时没有精确匹配”我是否需要使用数据而不是[String:String],如果是,如何使用?有人知道如何解决这个问题吗?提前谢谢

import SwiftUI

struct SpotDetailView: View {
    @State var spot: WindApp //knows which spot it's at
    var spotname:String
    //@State var favourites: [String:String] = UserDefaults.standard.object(forKey: "heart") as? [String:String] ?? [:]
    @AppStorage("heart") var favourites: [String: String] = [:]

        
    var body: some View {
        
        ZStack {
            
            List {
                SpotMapView(coordinate: spot.locationCoordinate)
                    .cornerRadius(8)
                ForEach(0..<9) { i in
                    SingleDayView(spot: spot, counter: (i * 8))
                    }
            }
            .navigationTitle("\(spot.spot)")
            VStack {
                Spacer()
                HStack {
                    Spacer()
                    Button(action: {
                        if favourites[spot.spot] == "heart" {
                            favourites[spot.spot] = "heart.fill"
                            UserDefaults.standard.set(favourites, forKey: "heart")
                        }
                        else if favourites[spot.spot] == "heart.fill" {
                            favourites[spot.spot] = "heart"
                            UserDefaults.standard.set(favourites, forKey: "heart")
                        }
                        else {
                            favourites[spot.spot] = "heart.fill"
                            UserDefaults.standard.set(favourites, forKey: "heart")
                        }
                
                    }, label: {
                        Image(systemName: favourites[spot.spot] ?? "heart")
                    })
                    .frame(width: 20, height: 20)
                }
            }
        }
    }
}
导入快捷界面
结构SpotDetailView:视图{
@State var spot:WindApp//知道它位于哪个位置
变量spotname:String
//@State-var-favorites:[String:String]=UserDefaults.standard.object(forKey:“heart”)为?[String:String]??[:]
@AppStorage(“heart”)变量收藏夹:[String:String]=[:]
var body:一些观点{
ZStack{
名单{
SpotMapView(坐标:spot.LOCATION坐标)
.转弯半径(8)

ForEach(0..您必须使用数据。@AppStorage当前仅支持:

  • Int
  • 双重的
  • 布尔
  • 网址
  • 资料

查看此答案以了解

此答案是否回答了您的问题?