A O A O - 1 year ago 54
Swift Question

Is this the correct way to enumerate over an array, looking for a potential object to store into a variable?

I was struggling to come up with a concise title, but I think the problem is pretty straight forward:

var selectedModule: Module? = nil
for module in ModuleList.modulesArray {
if module.name == selectedModuleName {
selectedModule = module
if let moduleFound = selectedModule {
_set(model: &viewModel.module, button: moduleButton, displayedValue: selectedModuleName, actualValue: moduleFound)

This is what I have now, and it works, but I come from Obj-C and this feels weird

I want to enumerate over
, and potentially store an object into

This of course means that
could be
, so I made it an Optional

But then I have to go and unwrap it with optional binding,
if let moduleFound = selectedModule

Is this really the best way to go about this?
Seems to be the case, but I'm just double-checking as I am very new to Swift

Thanks for your time!

Answer Source

No, that is not the best solution. The optional variable can be avoided completely.

If you are only interested in the first matching module then you can use the first(where:) method which returns the first element satisfying the predicate, or nil if no such element exists. The return value is checked with optional binding:

if let selectedModule = modulesArray.first(where: { $0.name == selectedModuleName }) {
    // Do something with selectedModule ...
} else {
    // No matching module

If you are interested in all matching modules then you can use a for loop with a where constraint:

for module in modulesArray where module.name == selectedModuleName {
    // Do something with module ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download