WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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

   

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.

   

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!

   

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

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

Reply to this topic…

You need to create an account or log in to reply.

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.