SwiftUI -环境变量:无法分配给属性:'xxx'是一个只获取属性

d8tt03nd  于 2023-03-22  发布在  Swift
关注(0)|答案(1)|浏览(109)

我正在尝试设置一个环境变量,如下文档:https://developer.apple.com/documentation/swiftui/environmentvalues
这是我的代码--
App.swift:

@main
struct GiniAppsApp: App {
    let persistenceController = PersistenceController.shared

        
    var body: some Scene {

        WindowGroup {
            
            ContentView()
                .environment(\.managedObjectContext, persistenceController.container.viewContext)
                .environment(\.hits, [])
        }
    }
}

private struct HitsArrayKey: EnvironmentKey {
    static let defaultValue: [Hit] = []
}

extension EnvironmentValues {
    var hits : [Hit] {
        get { self[HitsArrayKey.self] }
        set { self[HitsArrayKey.self] = newValue }
    }
}

extension View {
    func myCustomValue(_ myCustomValue: [Hit]) -> some View {
        environment(\.hits, myCustomValue)
    }
}

但是当我试图在视图中更改\更新变量时,我得到错误-

  • 〉无法分配给属性:'hits'是一个只获取属性 *

下面是视图的代码:

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @Environment(\.hits) private var hits: [Hit]
    
    var body: some View {
        
        Button(action: addItem) {
                        Label("GET", systemImage: "plus")
                        hits = []   //ERROR: Cannot assign to property: 'hits' is a get-only property 
                    }
        ...
gk7wooem

gk7wooem1#

通常,更改环境变量值的方法如下:

.environment(\.hits, [])

因为你有一个自定义的修饰符,你也可以使用

.myCustomValue([])

相关问题