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相关问答推荐

组合 flatMap 不会返回预期的上下文结果类型

What is "SwiftPM.SPMRepositoryError error 5"?

在 iOS 中使用 Swift 保存 PDF 文件并显示它们

Swift 中的 PageViewController 当前页面索引

UITableViewCell 不显示 detailTextLabel.text - Swift

是 swift 中另一个日期的同一周、月、年的日期

Swift中字节数组的NSData

iPhone 纵向和 iPad 横向的通用应用程序

在 IOS 项目中放置 .txt 文件并从中读取的位置

覆盖 Swift 2 中的 func 错误

swift中类的属性列表

如何从 Swift 中的 ASCII 码中获取字符串?

如何从 Swift 中的 indexPath 获取 UITableViewCell 对象?

RLMException,对象类型需要迁移

为什么 Swift 中没有通用基类?

在回调中以编程方式推送视图,SwiftUI

点击 UITextField 时没有出现 UIKeyboard

如何处理大型 Swift 项目?

在 Swift iOS 中使用 OpenCV

更改导航栏标题字体 - swift