https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
a

Alex

06/21/2021, 7:46 AM
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

okarm

06/21/2021, 9:07 PM
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

Alex

06/22/2021, 8:31 AM
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

okarm

06/22/2021, 9:25 AM
Your way is better, I’ll use that 👌
🙌 1
14 Views