Quantcast
Viewing all articles
Browse latest Browse all 4

Answer by green_knight for SwiftUI build a list using enums

You don't need Identifiable here. I've added selections as well, because why not:

enum Whatever: String, CaseIterable {    case one    case two}struct ContentView: View {  @Binding var selection: Whatever?    var body: some View {        VStack {            List (Whatever.allCases, id: \.rawValue, selection: $selection) { item in                Text(item.rawValue).tag(item)            }        }    }}

Selection has to be optional (the error messages here are not overly helpful), but this is basically how you get a list that changes an enum value. You can also use this for type erasure to display sublists of different data types in a sidebar (eg books, magazines, videos): use an enum with associated data, group by enum case, and enjoy.It is not necessary for id to be a static property; if your case is one(content: Book)you can have a computed id property with a switch statement and case one(let book): return book.id, and simply use an id: .id key path. (Unless elsewhere in Swift 5, the return keyword he remains mandatory).


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>