Mahi
Mahi

Reputation: 21969

Use same loop to iterate over multiple arrays subsequently?

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?

Upvotes: 0

Views: 31

Answers (1)

Claudio
Claudio

Reputation: 5203

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)

Upvotes: 2

Related Questions