0

I would like to iterate over an array and if a value exists, I would like to return TRUE.

struct Loops {
    var loopStep: LoopStep
}

struct LoopStep {
    var template: [Template]
}

struct Template {
    var stepType: String
}

let templates: [Template]  = [Template(stepType: "FORM_ONE"), Template(stepType: "FORM_TWO")]
let loopStep = LoopStep(template: templates)

let incompleteSteps = [Loops(loopStep: loopStep)]

I have tried this using reduce however cannot make this syntax work

let result = incompleteSteps.reduce(true, $0.loopStep.template.stepType == "FORM_ONE" )
Harry Blue
  • 4,202
  • 10
  • 39
  • 78
  • 3
    Why not simply use `contains(where:)` ? – Compare https://stackoverflow.com/questions/29679486/shorthand-to-test-if-an-object-exists-in-an-array-for-swift – Martin R Jan 03 '19 at 09:01
  • 2
    Offtopic: If you got fixed values, you should use an enum. That way, it will be a lot easier :) – J. Doe Jan 03 '19 at 09:02
  • 1
    Unrelated: Avoid plurals in struct and class names : `Loop` instead of `Loops` – ielyamani Jan 03 '19 at 09:06

1 Answers1

2

You simply need to use contains(where:) to get a bool return value indicating whether an element matching a closure exists in the collection or not. Since template is an Array itself as well, you actually need to nest two contains(where:) calls if you want to find out if an array of Loops contains any Loops whose template array contains a Template with the matching requirement.

let result = incompleteSteps.contains(where: {$0.loopStep.template.contains(where: {$0.stepType == "FORM_ONE"})})
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116