Post

AppStorage에 문자열 배열을 사용하기 위한 Array에 Extension하기

AppStorage에 문자열 배열을 사용하기 위한 Array에 Extension하기

전체 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
    }
}
1
extension Array: RawRepresentable

Array 타입을 RawRepresentable 프로토콜을 준수하도록 확장하는 것.

이 프토토콜은 rawValue라는 연산 프로퍼티를 요구한다.

예시 코드에서는 배열을 String(JSON)으로 변환하도록 구현하고 있음.

1
 where Element: Codable

Array는 제네릭 타입인데 Array<Element>에서 Element가 어떤 타입이든 올 수 있지만 where Element: Codable을 추가해서 배열의 요소가 Codable을 준수하는 타입에만 RawRepresentable을 적용할 수 있도록 제한한다.

This post is licensed under CC BY 4.0 by the author.