Not sure if anyone else has hit this problem, I ha...
# multiplatform
a
Not sure if anyone else has hit this problem, I have a bunch of
enum
classes in the shared module that I'm trying to use in a
Picker
in iOS. I had no issues using the enums in Android, but the
Picker
in SwiftUI requires the class to conform to
CaseIterable
and
RawRepresentable
. This hits a bit of a brick wall because you can only implement the
RawRepresentable
interface within the source class and not in an extension, has anyone found a way around this or do you have to create two enum classes and map between them?
👀 1
o
You just need to make your enum
Identifiable
.
Copy code
extension MyKotlinEnum : Identifiable {
    public var id: String { name }
}

// in a View:

private var enumValues: [MyKotlinEnum] {
    var values: [MyKotlinEnum] = []
    let iterator: KotlinIterator = MyKotlinEnum.values().iterator()
    while (iterator.hasNext()) {
        values.append(iterator.next() as! MyKotlinEnum)
    }
    return values
}

@State private var selectedEnum: MyKotlinEnum = MyKotlinEnum.defaultValue


Picker("", selection: $selectedEnum) {
    ForEach(enumValues) { enum in
        Text(enum.name).tag(enum)
    }
}
🙌 1
a
Thanks for your help on this, I got it working a slightly different way, sharing just for anyone else that hits this issue: Enum in shared module:
Copy code
enum class Region(val text: String) {
    ENGLAND("England"),
    SCOTLAND("Scotland"),
    WALES("Wales"),
    NI("Northern Ireland");

    override fun toString(): String = text
}
Extension:
Copy code
extension Region : Identifiable, CaseIterable {
    public var id: String { text }
    public static var allCases: [Region] {
        return [
            .england,
            .ni,
            .scotland,
            .wales
        ]
    }
}
View:
Copy code
@State private var selectedRegion = Region.england

Picker("Region", selection: $selectedRegion) {
  ForEach(Region.allCases) { value in
    Text(value.id).tag(value)
  }
}
Keeping the
CaseIterable
implementation means that the
.allCases
can be used in the Picker rather than writing any iterators ourselves
o
Your way is better, I’ll use that 👌
🙌 1