Swift如何使用索引[i]的for循环读取数组的所有索引

时间:2018-03-19 17:56:51

标签: arrays swift for-loop arraylist element

我到目前为止的代码仅针对1个索引,但是我希望它能够读取数组中的所有现有索引。例如,元素数组可以携带许多数字组 数组[" 2,2,5" ," 5,2,1"]包含2个索引[0]和[1]

var element = Array[0]
let splitData = element.components(separatedBy: ",")

// split data will always contain 3 values.
var value1 = splitData[0]
var value2 = splitData[1]
var value3 = splitData[2]

print("value 1 is : " + value1 + " value 2 is : " + value2 + " value 3 is: " + value3)
Array ["2,2,5" , "5,2,1"]为:

时,

此代码的输出

value 1 is : 2 value 2 is : 2 value 3 is : 5

如输出所示,我如何遍历Array的所有索引以显示其3个值中的每一个。

我希望输出为:

value 1 is : 2 value 2 is : 2 value 3 is : 5
value 1 is : 5 value 2 is : 2 value 3 is : 1

我相信我需要使用for循环但是我不确定如何将它应用于此。我对编码很陌生。任何帮助都将得到赞赏

2 个答案:

答案 0 :(得分:4)

这里有两个你可以使用的解决方案,具体取决于你的最佳结果。

1)如果您的目标是将["3,4,5", "5,6", "1", "4,9,0"]这样的数组转换为展平版本["3", "4", "5", "5", "6", "1", "4", "9", "0"],则可以使用flatMap运算符轻松完成以下方式:

let myArray = ["3,4,5", "5,6", "1", "4,9,0"]
let flattenedArray = myArray.flatMap { $0.components(separatedBy: ",") }

然后你可以像其他所有数组一样迭代它,

for (index, element) in myArray.enumerated() {
    print("value \(index) is: \(element)")
}

2)如果你只想迭代并保持关卡,你可以使用以下代码。

let myArray = ["3,4,5", "5,6", "1", "4,9,0"]

for elementsSeparatedByCommas in myArray {
    let elements = elementsSeparatedByCommas.components(separatedBy: ",")
    print(elements.enumerated().map { "value \($0) is: \($1)" }.joined(separator: " "))
}

希望有所帮助!

答案 1 :(得分:2)

for i in 0..<array.count {
    var element = array[i]
    let splitData = element.components(separatedBy: ",")

    // split data will always contain 3 values.
    var value1 = splitData[0]
    var value2 = splitData[1]
    var value3 = splitData[2]

    print("value 1 is : " + value1 + " value 2 is : " + value2 + " value 3 is: " + value3)
}