Codable with string array

Viewed 44

This question is more of an aesthetic one. I have a simple Codable with a string array. I use it to encode and decode a plist:

struct Favorites: Codable {
  var favorites: [String]
}

The one thing that bothers me about this is when I e.g. add an element to the array, I have to do this:

favorites.favorites += [phrase]

Is there something I can do to prevent having to write the double favorites.favorites?

1 Answers

If you want to avoid writing favorites two times, you can add subscript to your Favorites struct and also add mutating method to add items in your array.

struct Favorites: Codable {
    var favorites: [String]
    
    subscript(index: Int) -> String {
        favorites[index]
    }
    
    mutating func addItem(_ item: String) {
        favorites.append(item)
    }
    
    mutating func addItems(_ items: [String]) {
        favorites.append(contentsOf: items)
    }
}

Now your can access your favorites array as with instance of Favorites struct using subscript like this.

var favorites = Favorites(favorites: ["Apple"])
print(favorites[0]) // print Apple
favorites.addItem("Banana")
print(favorites[1])// print Banana
Related