for循环变量名使用swift

时间:2015-07-02 03:58:32

标签: swift variables for-loop

我有静态变量名,我想创建它使用循环:

var imageke1 = ""
var imageke2 = ""
var imageke3 = ""
var imageke4 = ""
var imageke5 = ""
var imageke6 = ""
var imageke7 = ""

我尝试使用此功能但创建错误预期模式:

for var i = 1; i < 8; i++
    {
        var "imageke\(i)" = ""
    }

我也尝试过这个但它与相同的变量名称(kucing)冲突:

for var i = 1; i < 8; i++
    {
        var kucing = "imageke\(i)"
        var kucing = ""
    }

最后我还创建了一个字符串列表作为结果,我想用loop更改它:

var names: [String] = ["\(imageke1)", "\(imageke2)", "\(imageke3)", "\(imageke4)", "\(imageke5)", "\(imageke6)", "\(imageke7)"]

如何循环此变量名称(imageke)和var名称?

2 个答案:

答案 0 :(得分:0)

您应该使用字符串数组而不是手动检索变量。

var imageke = [String]() //remember to set your arraySize, or append new elements
// to set 
for var i = 1; i < 8; i++
{
    imageke[i] = "some value here"
}

答案 1 :(得分:0)

var names: [String] = []

for index in 1...8 {
    names.append("imageke\(index)")
}

println(names)  // "[imageke1, imageke2, imageke3, imageke4, imageke5, imageke6, imageke7, imageke8]"