Skip to content

Instantly share code, notes, and snippets.

@cmsj
Created August 21, 2020 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmsj/cfa255cde9483dc5019d8b4259b9cfc9 to your computer and use it in GitHub Desktop.
Save cmsj/cfa255cde9483dc5019d8b4259b9cfc9 to your computer and use it in GitHub Desktop.
Extending someone else's Swift enum to make it more friendly for a SwiftUI Picker
//
// ContentView.swift
// EnumExtensionPicker
//
// Created by Chris Jones on 21/08/2020.
//
import SwiftUI
enum Strategy {
case red
case blue
case none
}
class SomeThirdPartyThing {
var strategy: Strategy
init() {
strategy = .none
}
}
// The magic starts
extension Strategy: CaseIterable, Identifiable {
var id: Strategy { self }
var customString: String {
switch self {
case .none:
return "None"
case .red:
return "Red"
case .blue:
return "Blue"
}
}
}
// The magic ends
var theClass = SomeThirdPartyThing()
struct ContentView: View {
let strategyBinding: Binding<Strategy>
init() {
strategyBinding = Binding<Strategy>(
get: { return theClass.strategy },
set: {
print("Setting new value to theClass: \($0.customString)")
theClass.strategy = $0
}
)
}
var body: some View {
Picker("Strategy", selection: strategyBinding) {
ForEach(Strategy.allCases) { strategy in
Text(strategy.customString).tag(strategy)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment