this post was submitted on 05 Jul 2023
2 points (75.0% liked)

Swift

340 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!

top 1 comments
sorted by: hot top controversial new old
[–] [email protected] 2 points 11 months ago* (last edited 11 months ago)

It feels like what you’re trying to do would be better using a dictionary with the index being the element hash instead of a linear array.