Use @AppStorage with Arrays

Hey,

I know you can write @AppStorage("username") var username: String = "Anonymous" to access a Value, stored In the User Defaults, and you can also overwrite him by changing the value of username.

I was wondering if there is any workaround to use @AppStorage with Arrays.

Because I don't find anything, but I have a lot of situations where I would use it.

Thanks! Max

unfortunately, nope. the work around is to do something like

class SearchHistory {
    private static let maxHistoryItems = 50
    
    @AppStorage("searchHistory") private var historyData: Data = Data()
    
    var recentSearches: [SearchHistoryItem] {
        get {
            guard let items = try? JSONDecoder().decode([SearchHistoryItem].self, from: historyData)
            else { return [] }
            return items
        }
        set {
            let limitedItems = Array(newValue.prefix(Self.maxHistoryItems))
            if let data = try? JSONEncoder().encode(limitedItems) {
                historyData = data
            }
        }
    }
}

I had to store a Set<String> in @AppStorage and ended up using the following code:

extension Set: @retroactive RawRepresentable where Element == String {
    public init?(rawValue: String) {
        guard let data = rawValue.data(using: .utf8),
              let decoded = try? JSONDecoder().decode(Set<String>.self, from: data) else {
            return nil
        }
        self = decoded
    }

    public var rawValue: String {
        guard let data = try? JSONEncoder().encode(self),
              let json = String(data: data, encoding: .utf8) else {
            return "[]"
        }
        return json
    }
}

With that in place, I was then able to do the following:

@AppStorage("tags") private var selectedTags: Set<String> = []
Use &#64;AppStorage with Arrays
 
 
Q