Thread
#multiplatform
    Alex

    Alex

    1 year ago
    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?
    o

    okarm

    1 year ago
    You just need to make your enum
    Identifiable
    .
    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)
        }
    }
    Alex

    Alex

    1 year ago
    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:
    enum class Region(val text: String) {
        ENGLAND("England"),
        SCOTLAND("Scotland"),
        WALES("Wales"),
        NI("Northern Ireland");
    
        override fun toString(): String = text
    }
    Extension:
    extension Region : Identifiable, CaseIterable {
        public var id: String { text }
        public static var allCases: [Region] {
            return [
                .england,
                .ni,
                .scotland,
                .wales
            ]
        }
    }
    View:
    @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

    1 year ago
    Your way is better, I’ll use that 👌