Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making Picker compatible with other BinaryInteger types

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)
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading