AppStorage extension for Bool Arrays

Hi,

As AppStorage does not support arrays, I found an extension online that allows for handling arrays of strings with AppStorage. However, in my use case, I need to handle arrays of boolean values. Below is the code. Any help would be greatly appreciated.

extension Array: RawRepresentable where Element: Codable {
    public init?(rawValue: String) {
        guard let data = rawValue.data(using: .utf8),
              let result = try? JSONDecoder().decode([Element].self, from: data)
        else {
            return nil
        }
        self = result
    }

    public var rawValue: String {
        guard let data = try? JSONEncoder().encode(self),
              let result = String(data: data, encoding: .utf8)
        else {
            return "[]"
        }
        return result
    }
}
Answered by Claude31 in 800430022

I need to handle arrays of boolean values.

There is a very simple solution:

  • convert true / false to "T", "F" and handle as String. map() let do it at once.
  • Convert back when you need to use the Bool values. Here again, map() is your friend.
Accepted Answer

I need to handle arrays of boolean values.

There is a very simple solution:

  • convert true / false to "T", "F" and handle as String. map() let do it at once.
  • Convert back when you need to use the Bool values. Here again, map() is your friend.
AppStorage extension for Bool Arrays
 
 
Q