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

问题描述

嘿,在我的应用程序中,我试图存储用户是否希望某个位置成为其最喜欢的位置。为了使此 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)
                }
            }
        }
    }
}

解决方法

您将不得不使用数据。 @AppStorage 目前仅支持:

  • 内部
  • 双人
  • 字符串
  • 布尔
  • 网址
  • 数据

查看sample implementation and further details

的这个答案