Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Codable with string array

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading