Extending someone else's Swift enum to make it more friendly for a SwiftUI Picker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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