Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does _ and .. mean in a for loop?

Tags:

swift

I'm doing the A Swift Tour.

One:

I'm not getting the Generics functions logic. Its for Design Patterns? And the explanation on the tour looks very short and unclear.

Two:

In this pice of code for creating a generic function,

func repeatItem<Item>(item: Item, numberOfTimes: Int) -> [Item] {
    var result = [Item]()
    for _ in 0..<numberOfTimes { //im not getting this line (?)
        result.append(item)
    }
    return result
}
repeatItem("knock", numberOfTimes:4)

I do not understand this syntax very well, what means _, .., and < in the same line, why is used?

like image 722
Andre Avatar asked Nov 28 '25 15:11

Andre


1 Answers

_, .., and < are not part of the generics.

_ is just an non-name for a parameter that is never used. usually you would put a variable name like i there and use it in the block but as you are just doing something a certain number of times you are not really using the index.

..< is a shorthand for the range between the start value and the end value. 1..<5 would then generate the range 1,2,3,4

there is also a range shorthand ... that gives you the last value 5

Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner. Generics

like image 93
Moriya Avatar answered Nov 30 '25 04:11

Moriya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!