Picker only works properly when used with Int, when using any other type of BinaryInteger it doesn't update the selection at all. To remedy this, I want to make a CompatilibityPicker but I must admit my understanding of how Bindings actually work is causing me a lot of trouble. Here is my current code :

struct CompatibilityPicker<Label, SelectionValue, Content> : View where Label : View, SelectionValue : BinaryInteger, Content : View {

    var content : () -> Content
    var label : Label

    @Binding var _selection : SelectionValue

    var selection : Int {
        get {
            Int(_selection)
        }
        set {
            self._selection = SelectionValue(newValue)
        }
    }

    var body: some View {
        // This line shows errors about selection and I don't know how to fix them,
        // using $selection does not work either.
        Picker(label, selection: selection, content: content)
    }
}

推荐答案

Here is fixed variant - separated external binding and internal proxy binding to make transform

struct CompatibilityPicker<Label, SelectionValue, Content>: View where Label : View, SelectionValue : BinaryInteger, Content : View {

    var content : () -> Content
    var label : Label

    @Binding var selection : SelectionValue

    private var value: Binding<Int> { Binding<Int>(
        get: {
            Int(selection)
        },
        set: {
            self.selection = SelectionValue($0)
        })
    }

    var body: some View {
        Picker(selection: value, content: content) { label }
    }
}

Swift相关问答推荐

SwiftUI正在初始化不带状态变量的绑定变量

它是RxSwift中直接用于可扩展视图的有效的可扩展BehaviorRelay值?

使用MKLocalSearch获取坐标

字典下标或运算符,如果密钥不存在,则添加指定的默认&值是SWIFT?

如何获取嵌套数组中项的路径以修改数组?

在 SwiftUI 视图中观察 UIViewRepresentable 的 @State var 变化

PassthroughSubject 的 AsyncPublisher 值属性未生成所有值

使用 swift 的 Firebase 身份验证

Firebase removeObserver 在 Swift 5 中不起作用

并发执行代码中捕获的 var 的变异

UUID 哈希值是不确定的吗?

iOS SwiftUI - 无法转换 ObservedObject 类型的值

符合协议 - 错误?

我如何从 UIAlertController 导航到新屏幕(swiftUI)

NSFontAttributeName 已更改为 String

Swift 动画 WithDuration 语法是什么?

Swift 自定义字体 Xcode

使用 DispatchTime.now() + float 延迟?

使用 ARAnchor 插入 node 和直接插入 node 有什么区别?

在 Swift 中子类化 NSObject - 初始化器的最佳实践