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
            }
        }
    }
}
Use @AppStorage with Arrays
 
 
Q