Alex
06/21/2021, 7:46 AMenum
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?okarm
06/21/2021, 9:07 PMIdentifiable
.
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
06/22/2021, 8:31 AMenum 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 ourselvesokarm
06/22/2021, 9:25 AM