SwiftUI @State 奇怪的 wrappedValue 行为

SwiftUI @State wierd wrappedValue behaviour

开门见山,我有这段代码:

struct DataModel {
    var option: String

}

struct ViewModel {
    var selected: String? = "1"
    var options = [DataModel(option: "1"), DataModel(option: "2"), DataModel(option: "3")]
}

struct ContentView: View {
    
    @State var viewModel: ViewModel
    
    var body: some View {
        VStack {
            Picker("test", selection: aBinder()) {
                ForEach(viewModel.options, id: \.option) { option in
                    Text(option.option)
                }
            }
            .background(Color.red)
        }
    }
    
    func aBinder() -> Binding<String?> {
        Binding<String?> {
            viewModel.selected
        } set: { value in
            $viewModel.selected.wrappedValue = value
            print($viewModel.selected.wrappedValue)
        }
    }
}

viewModel 中“selected”的值不变。

这个有效:

struct DataModel {
    var option: String
}

struct ViewModel {
    var selected: String = "1"
    var options = [DataModel(option: "1"), DataModel(option: "2"), DataModel(option: "3")]
}

struct ContentView: View {
    
    @State var viewModel: ViewModel
    
    var body: some View {
        VStack {
            Picker("test", selection: $viewModel.selected) {
                ForEach(viewModel.options, id: \.option) { option in
                    Text(option.option)
                }
            }
            
            Button("press me", action: { print(viewModel.selected) })
        }
    }
}

但这没有任何意义。在这两种情况下,我都使用绑定来存储当前值。到底是怎么回事?我是 swiftUI 的新手,所以我可能错过了一些东西是如何工作的。

提前致谢

类型不匹配 selectedStringoptionsDataModel。类型必须完全匹配。