You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@Observable与@Environment结合Swift Macros编译报错,如何解决?

解决@Observable与@Environment结合时的Binding问题

问题原因

@Environment(Note.self) 获取的是 Note 实例本身,而非 Binding<Note>,因此无法使用 $note 语法;直接传入 note.text 是 String 类型,不符合 TextField 所需的 Binding<String> 参数要求。

解决方案

方法一:直接用Bindable包装实例获取属性Binding

修改FormView的body部分,通过Bindable结构体包装note实例,进而获取属性的Binding:

struct FormView: View {
    @Environment(Note.self) var note
    
    var body: some View {
        Form {
            TextField("write here", text: Bindable(note).$text)
        }
    }
}

方法二:使用@Bindable属性包装器(iOS 17+/macOS 14+)

在FormView中用@Bindable包装环境注入的note,之后即可通过$语法访问属性Binding:

struct FormView: View {
    @Environment(Note.self) private var note
    @Bindable private var bindableNote: Note { note }
    
    var body: some View {
        Form {
            TextField("write here", text: $bindableNote.text)
        }
    }
}

完整可运行代码

import SwiftUI
import Observation

@Observable class Note {
    var text = ""
}

struct ContentView: View {
    @State var note = Note()
    
    var body: some View {
        FormView()
            .environment(note)
    }
}

struct FormView: View {
    @Environment(Note.self) var note
    
    var body: some View {
        Form {
            TextField("write here", text: Bindable(note).$text)
        }
    }
}

内容的提问来源于stack exchange,提问作者ygee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:05:28