Search code examples
swiftuiappstorage

How to store EnumTypes with @AppStorage in SwiftUI


I want to store a map-status in UserDefaults. Is it possible to do something like this:

@AppStorage("myMapType") var mapType: MKMapType = .standard

Or do I have to access the rawValue of the MKMapType instead? How could I do this?


Solution

  • import SwiftUI
    import MapKit
    struct MapTypeSwitcherView: View {
        @AppStorage("myMapType") var mapType: Int = 0
        let mapCases: [MKMapType] = [.hybrid,.hybridFlyover, .mutedStandard,.satellite,.satelliteFlyover,.standard]
        var body: some View {
            VStack{
                MapViewUIKit()
                ForEach(mapCases, id: \.self ){ type in
                    Button(type.rawValue.description, action: {
                        mapType = Int(type.rawValue)
                    })
                }
            }
        }
    }
    struct MapViewUIKit: UIViewRepresentable {
        @AppStorage("myMapType") var mapType: Int = 0
    
        func makeUIView(context: Context) -> MKMapView {
            let mapView = MKMapView()
            mapView.mapType = MKMapType(rawValue: UInt(mapType)) ?? .standard
            return mapView
        }
        
        func updateUIView(_ mapView: MKMapView, context: Context) {
            mapView.mapType = MKMapType(rawValue: UInt(mapType)) ?? .standard
        }
    }
    

    If it is a custom enumthat you can make conform to Codable it can be much simpler

    enum MyValues: String, Codable, CaseIterable{
        case first
        case second
        case third
    }
    struct NewListView: View {
        @AppStorage("myEnumType") var enumType: MyValues = .first
        var body: some View {
            VStack{
                Text("Hello World!")
                Text(enumType.rawValue)
                Picker("myEnums", selection: $enumType, content: {
                    ForEach(MyValues.allCases, id: \.self, content: { item in
                        Text(item.rawValue).tag(item)
                    })
                })
            }
        }
    }