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

Vic*_*ann 2 xcode swift swiftui appstorage

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

小智 6

您可以使 Dictionary [String:String] 符合 RawRepresentable。

extension Dictionary: RawRepresentable where Key == String, Value == String {
    public init?(rawValue: String) {
        guard let data = rawValue.data(using: .utf8),  // convert from String to Data
            let result = try? JSONDecoder().decode([String:String].self, from: data)
        else {
            return nil
        }
        self = result
    }

    public var rawValue: String {
        guard let data = try? JSONEncoder().encode(self),   // data is  Data type
              let result = String(data: data, encoding: .utf8) // coerce NSData to String
        else {
            return "{}"  // empty Dictionary resprenseted as String
        }
        return result
    }

}
Run Code Online (Sandbox Code Playgroud)