简体   繁体   English

快速3循环错误(获取变量并自行添加)

[英]swift 3 loop error (taking variable and adding it by itself)

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])
}

Because Any doesn't have + operator. 因为Any没有+运算符。

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 如果要添加2个值并打印结果,则需要将Any为可计算值,例如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)
    }
}

The use of as [Any] makes no sense. 使用as [Any]没有任何意义。 You can't add two objects of type Any which is probably what your error is about. 您不能添加两个Any类型的对象,这可能是您的错误所在。

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 4.0
6.0 6.0
16.0 16.0

Better yet: 更好的是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM