labnxx labnxx - 2 months ago 9
Swift Question

How to concatenate a string with a count variable and an increment operator in a print statement?

I have a string variable. I need the variable to change. What I thought of was to declare a count variable with an increment operator. I used it in a print statement but it doesn't work.

I need it to print iOS1 to iOS10 but instead it just prints iOS ten times.

Basically I need it to print 10 different strings based off of the one iOS variable.

let iOS = "iOS"

var count = 0

for num in 1...10 {
print("\(iOS)" + String(count += 1))
}

/*
I want to print
iOS1
iOS2
iOS3
iOS4
iOS5
iOS6
iOS7
iOS8
iOS9
iOS10
*/


I also tried to use string interpolation but nahhh it didn't work either

for num in 1...10 {
print("\(iOS)" + "String(\(count += 1))")
}

Answer

Just use the index variable num. It's incremented automatically

let iOS = "iOS"

for num in 1...10 {
  print("\(iOS)\(num)")
}

or

(1...10).forEach { print(iOS + "\($0)") }

PS: Use this if the count variable is required

var count = 0

for _ in 1...10 {
  count += 1
  print(iOS + "\(count)")
}
Comments