MultiPicker icon indicating copy to clipboard operation
MultiPicker copied to clipboard

Custom Struct

Open jan-martenn opened this issue 1 year ago • 0 comments

Situation

Wrong initialiser used when I was using this struct:

struct CurrencyPair: Hashable, Identifiable, Codable {
    var id: String { description }
    
    var base: String
    var quote: String
    var enabled: Bool
    
    var description: String {
        "\(base)/\(quote)"
    }
}

with this code:

@State private var currencyPairSelection: Set<CurrencyPair>
@State private var currencyPairOptions: [CurrencyPair]

var settings: Settings

init(settings: Settings) {
    self.settings = settings
    _currencyPairOptions = State(initialValue: settings.currencyPairs)
    
    let set =  Set(settings.currencyPairs.filter { $0.enabled })
    _currencyPairSelection = State(initialValue: set)
}

            MultiPicker(selection: $currencyPairSelection, content: {
                ForEach(currencyPairOptions, id: \.self) { option in
                    Text(option.description).mpTag(option)
                }
            }, label: {
                Text("Enabled Currencies")
            })
            .mpPickerStyle(.navigationLink)

`

I wanted a Multiple option picker, but could not find the reason this was not working. So I CMD + Clicked on the MultiPicker to see what Initialiser was being used, turns out the selection property was set to single.

After I commented out the other intialisers except for the Binding<Set<>> one, Xcode finally gave the error that my struct needed to conform to CustomStringConvertible.

Finally, after adding this to the struct like this:

 struct CurrencyPair: Hashable, Identifiable, Codable, CustomStringConvertible {
    var id: String { description }
    
    var base: String
    var quote: String
    var enabled: Bool
    
    var description: String {
        "\(base)/\(quote)"
    }
}

it works perfectly!

Solution

Either add to the documentation that a custom struct must conform to CustomStringConvertible, or some kind of extra check to get the correct initialiser. Thanks!!

jan-martenn avatar May 20 '24 12:05 jan-martenn