Created
June 14, 2020 20:18
-
-
Save nbasham/58802c851a8269c818707fc63f29cb54 to your computer and use it in GitHub Desktop.
Enum to list example
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
import SwiftUI | |
public enum Enum1: Int, Codable, CaseIterable, CustomStringConvertible { | |
public var description: String { | |
return "\(rawValue)" | |
} | |
case one, two, three | |
} | |
public enum Enum2: String, Codable, CaseIterable, CustomStringConvertible { | |
public var description: String { | |
return "\(rawValue)" | |
} | |
case a, b, c | |
} | |
struct ContentView: View { | |
@State private var enum1 = "" | |
@State private var enum2 = "" | |
var body: some View { | |
NavigationView { | |
Form { | |
Section(header: Text("Using extension")) { | |
Picker("enum1", selection: $enum1) { | |
List { Enum1.toForEach() } | |
} | |
Picker("enum2", selection: $enum2) { | |
List { Enum2.toForEach() } | |
} | |
} | |
Section(header: Text("Not using extension")) { | |
Picker("enum1", selection: $enum1) { | |
List { ForEach(Enum1.allCases, id: \.description) { o in Text(o.description) } } | |
} | |
Picker("enum2", selection: $enum2) { | |
List { ForEach(Enum2.allCases, id: \.description) { o in Text(o.description) } } | |
} | |
} | |
} | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} | |
extension CaseIterable where Self.AllCases: RandomAccessCollection, Self: Hashable & CustomStringConvertible { | |
static func toForEach() -> some View { | |
ForEach(Self.allCases, id: \.self) { o in | |
Text(o.description).tag(o) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment