Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift how to read through all indexes of array using for loop with index [i]

The Code I have so far only does for 1 index however I want it to read all existing indexes within the array. element array can carry many groups of numbers for example Array ["2,2,5" , "5,2,1"] contains 2 indexes [0] and [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)

the output of this code when Array ["2,2,5" , "5,2,1"] is :

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

As the output suggests how can i iterate through all indexes of Array to display each of their 3 values.

I want the output to be :

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

I believe I need to use a for loop however I am unsure how to apply it to this. I am quite new to coding. Any help will be Appreciated

like image 722
steve Avatar asked Dec 19 '22 00:12

steve


2 Answers

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)
}
like image 173
gmogames Avatar answered May 08 '23 09:05

gmogames


here are two solutions you can use, depending on what is the best result for you.

1) If your goal is to transform an array like ["3,4,5", "5,6", "1", "4,9,0"] into a flattened version ["3", "4", "5", "5", "6", "1", "4", "9", "0"] you can do it easily with the flatMap operator in the following way:

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

Then you can iterate on it like every other array,

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

2) If you just want to iterate over it and keep the levels you can use the following code.

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: " "))
}

Hope that helps!

like image 22
Julien Perrenoud Avatar answered May 08 '23 09:05

Julien Perrenoud