2

I'm very new to Swift and trying to figure out how to count up within a for loop. For example, why doesn't something like this work? I want it to print the new age +1 12 times over......

So ultimately it would read: I am now 36 years old I am now 37 years old etc...

var myAge = 35

for _ in 1...20{
    print("I am now \(myAge += 1) years old")
}

3 Answers 3

4

Swift does not support the syntax myAge += 1 inside string interpolation. You can do myAge++ instead.

var myAge = 35

for _ in 1...20 {
    print("I am now \(myAge++) years old")
}
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this will no longer work once Swift 3 is released. The ++ and -- operators have been deprecated. You can now do myAge += 1 on its own line inside the for loop, then print out myAge inside the print statement.
1

String interpolation attempts to describe a value, not evaluate an expression. Technically, it interpolates the result of calling .description - a String - on anything that conforms to CustomStringConvertible. See How can I change the textual representation displayed for a type in Swift?

So, considering it as a value, rather than an expression, what type do you expect myAge += 1 to be? If you add it explicitly, thus:

var myAge = 35

for _ in 1...20 {
    let x = (myAge += 1)
    print("I am now \(x) years old")
}

you will see that the compiler warns you :

"Constant x inferred to have type '()', which may be unexpected."

Comments

0

The code below works, apparently the print() constructor doesn't support +=, but you can update the value and then print your results.

var myAge = 35

for _ in 1...20{

    myAge += 1
    print("I am now \(myAge) years old")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.