Marcal
Marcal

Reputation: 1371

Populating Array in Swift 4 with for-loop without using the index

I need to populate an Array (already declared and initialized) using a for loop in order to create a determinate amount of items.

I ended up with the following code:

    func createValues() -> Array<Int> {

        let usableRange:Range = 6..<11;

        var arrayOfValues: Array<Int>=[]; //Array declared and initialized

        for i in 0..<10 {

            arrayOfValues.append(random(usableRange));

            print(arrayOfValues[i]);

        }

        return arrayOfValues;
    }

this code does what I expect it to do just fine. However, as soon as I comment out the line

 print(arrayOfValues[i]);

Xcode throws the following warning:

Immutable value 'i' was never used; consider replacing with '_' or removing it

If I accept the suggestion the code works, but not as fine as it did before.

I'm just transitioning from Obj-C to Swift and I don't really know what the proper way to do this should be. Any help would be appreciated. Thanks in advance.

P.S. I'm aware that I don't need semicolons anymore, but old habits die hard, I guess...

Upvotes: 0

Views: 1150

Answers (4)

Philip Niedertscheider
Philip Niedertscheider

Reputation: 1069

Array has a designated initalizer, which initalizes an array with a given size and a repeated value:

let values = Array(repeating: "VALUE", count: 5)
print(fiveZs)
// Prints "["VALUE", "VALUE", "VALUE", "VALUE", "VALUE"]"

Source: Apple Documentation

Upvotes: 0

matt
matt

Reputation: 536057

If the goal is to generate an array of random numbers in your given range, I would suggest you simply generate it directly. There is no need for the for loop.

let usableRange = UInt32(6)..<UInt32(11)
let arr = (0..<10).map { _ in Int(
    arc4random_uniform(usableRange.upperBound - usableRange.lowerBound) 
    + usableRange.lowerBound
)}

Upvotes: 0

gnasher729
gnasher729

Reputation: 52632

Since you don't use i, you can just write

for _ in 0 ..< 10

The _ means "yes, there is a value, but I don't care about it", here and in many other situations.

Upvotes: 1

If you want just a good alternative for your code, I'm offering you this:

var i: Int = 0

while i < 10 {

  arrayOfValues.append(random(usableRange))
  i += 1

}

Upvotes: 0

Related Questions