0

My code does not work right now. I am trying to take names and add it by itself in the loop but the complier is giving me a error message and the code is not being printed.

let names = [Double(2),3,8] as [Any]
let count = names.count
for i in 0..<count {
    print((names[i]) + names[i])
}
3
  • 1
    What is the error message? Commented Apr 21, 2017 at 23:02
  • 2
    What's the point of the as [Any]? Commented Apr 21, 2017 at 23:04
  • 1
    Well names is an [Any], so the elements could be, well, anything. You cannot add together arbitrary things – what if names[i] was a Bool? Commented Apr 21, 2017 at 23:04

2 Answers 2

1

Because Any doesn't have + operator.

This will give you the result you expected.

If you want to add 2 values and print the result, you need to cast Any to calculatable like Double

let names = [Double(2),3,8] as [Any]
let count = names.count
for i in 0..<count {
    if let value = names[i] as? Double {
        print(value + value)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

The use of as [Any] makes no sense. You can't add two objects of type Any which is probably what your error is about.

Simply drop it and your code works.

let names = [Double(2),3,8]
let count = names.count
for i in 0..<count {
    print(names[i] + names[i])
}

Output:

4.0
6.0
16.0

Better yet:

let names = [Double(2),3,8]
for num in names {
    print(num + num)
}

Comments

Your Answer

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