0

Not looking for zip(), as I have multiple arrays:

var cellphones = [IPhone(), Galaxy()]
var laptops = [Macbook(), Ideapad()]

And I want to iterate over them all in any order:

cellphones.forEach { device in
    var multiple = lines()
    ofCode()
    thatDontNeedToKnowIfPhoneOrLaptop(device)
}
laptops.forEach { device in
    var multiple = lines()
    ofCode()
    thatDontNeedToKnowIfPhoneOrLaptop(device)
 }

How would I do this without having to repeat the loop bodies?

1
  • 1
    What about creating a closure/func with the repeated code? Commented Jun 9, 2020 at 7:47

1 Answer 1

2

Assuming the objects on the array all implement the same protocol or inherit the same class I believe this would work:

let loop: ((DeviceProtocol) -> Void) = { device in
    var multiple = lines()
    ofCode()
    thatDontNeedToKnowIfPhoneOrLaptop(device)
}

cellphones.forEach(loop)
laptops.forEach(loop)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this actually solves my problem even better than the solution I asked for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.