UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Storing an enum using @SceneStorage

Forums > SwiftUI

I am trying to store the value of an enumeration using the @SceneStorage property wrapper.

It is a macOS app, and I am doing this because the sidebar of the app I am playing around with represents documents that may be grouped in Core Data by some group ID (like a folder ID), or they may be pseudo- or meta-groups of documents, such as "All" or "Recent". I would like my app to remember which document group is selected.

The enum looks like this:

enum DocumentGrouping {
    case all
    case recent
    case folder(UUID)
}

...and my @SceneStorage declaration looks like this:

@SceneStorage("selection") private var selectedDocumentGrouping: DocumentGrouping

However, Swift(UI) complains "No exact matches in call to initializer." How do I get around this?

Or, if this is not a good approach, how can I rework my sidebar's List(selection: $selectedDocumentGrouping) to best implement this?

Thanks! Mark

2      

Two things you need to do:

  1. Assign a default value to your @SceneStorage:
@SceneStorage("selection") private var selectedDocumentGrouping = DocumentGrouping.all
  1. Make DocumentGrouping conform to RawRepresentable so you can store the rawValue in @SceneStorage as a String.
extension DocumentGrouping: RawRepresentable {
    var rawValue: String {
        switch self {
        case .all: return "all"
        case .recent: return "recent"
        case let .folder(uuid): return uuid.uuidString
        }
    }

    init?(rawValue: String) {
        switch rawValue {
        case "all": self = .all
        case "recent": self = .recent
        case let uuidString:
            guard let uuid = UUID(uuidString: uuidString) else {
                return nil
            }
            self = .folder(uuid)
        }
    }
}

That should work.

3      

Awesome, that compiles although I won't know until tomorrow if it is functioning as expected.

I had just started going down the Codable route rather than the RawRepresentable one; so thank you!

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.