Reputation: 21969
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
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