Is there anyway to use a loop to shorten this code

This is the code I am trying to shorten. I would think there is a loop for it but I am not sure.

        piker1.tag = 1
        piker2.tag = 2
        piker3.tag = 3
        piker4.tag = 4
        piker5.tag = 5
        piker6.tag = 6
        piker7.tag = 7
        piker8.tag = 8
        piker9.tag = 9
        piker10.tag = 10
        piker11.tag = 11
        piker12.tag = 12
        piker13.tag = 13
        piker14.tag = 14

@zalubski Thanks very much for posting your question!

In terms of coming up with an efficient solution to this problem, what I would suggest is to

  1. Put the piker (I’m guessing you mean “picker”) into an array:

let pikers = [piker1, piker2, piker3,…]

  1. Now use the zip function, along with the indices:

zip(pikers, 1 …< pikers.count).forEach{ $0.0.tag = $0.1 }

In the line, “$0.0.tag” the first property $0 refers to the tuple itself that is created from the zip function, the next value, 0, refers to the “piker”, which then has the tag property.

I hope this makes sense. Try it out and see how it works :slight_smile:

All the best!

The whole concept of doing what you’re asking for is bad coding practice, im convinced you can solve your problem in a much more efficient way. This is a typical use for a simple array, where the index will correspond for the picker number you want to address. Have you tried that approach?

This topic was automatically closed after 166 days. New replies are no longer allowed.