K Abdulahi
K Abdulahi

Reputation: 63

Execute line of code n times without initializing a variable

I'm new to swift. I want to add 100 random integers to an array. I have the following working code:

var integers = [Int]()

for i in 1...100 {
  integers.append((Int.random(in: 0 ..< 100)))
}

The compiler warns me that I did not use i inside the scope of the for loop, which is indeed a sensible warning. Is there a way to do some line n times without declaring a variable which I won't use anyway?

Upvotes: 1

Views: 222

Answers (3)

ielyamani
ielyamani

Reputation: 18591

You could do it like so:

let integers = (1...100).map { _ in Int.random(in: 0..<100) }

Upvotes: 1

Sweeper
Sweeper

Reputation: 272905

Change the i with _.

_ is just a way of saying that you don't need a variable here. It is known as the "wildcard pattern" in the swift documentation:

A wildcard pattern matches and ignores any value and consists of an underscore (_). Use a wildcard pattern when you don’t care about the values being matched against. For example, the following code iterates through the closed range 1...3, ignoring the current value of the range on each iteration of the loop:

for _ in 1...3 {
    // Do something three times. 
}

Upvotes: 2

rmaddy
rmaddy

Reputation: 318884

Change i to _. The use of the underscore is a way to tell the Swift compiler that you don't care about the variable or return value.

You can find this in the Swift book in the Control Flow chapter under For-In Loops.

Upvotes: 2

Related Questions