this post was submitted on 05 Jul 2023
0 points (50.0% liked)

Swift

352 readers
1 users here now

This group focus on the content related to the development of Apple Eco-system software. So feel free to share and talk about, for example;

founded 1 year ago
MODERATORS
 

So I've got the following code, which seems to work, and I'm wondering if there is a better, cleaner way to approach adding/editing elements in an array.

var category: Category
var idx: Int = -1

switch mode {
case .add:
    category = Category()
case .edit(let _category):
    category = _category
    idx = categoryViewModel.categories.firstIndex(of: _category) ?? idx
}

category.name = categoryName
category.icon = "category-\(categoryIdx)"
category.color = colors[colorIdx]

switch mode {
case .add:
    categoryViewModel.categories.append(category)
case .edit:
    categoryViewModel.categories[idx] = category
}

I understand I'm not checking idx to make sure it's not -1. I'm not concerned about that part right now. It's the overall approach I'm looking for thoughts on.

Thanks!

no comments (yet)
sorted by: hot top controversial new old
there doesn't seem to be anything here