JL GallardoV
JL GallardoV

Reputation: 13

Convert string elements to int elements in an array in swift

I have a string with the following format:

var cadenaCoordenadas = """
1,1
1,3
4,1
5,1
1,5
1,6
2,5
0,0
"""

What I want is that each line is in the following format (in an array) to manipulate it (with Int data types as I will do operations with the new string): [1,1]

I have the following code:

var arregloEntradas = cadenaCoordenadas.split(separator: "\n")
print("primer Arreglo: ", arregloEntradas)
for i in stride(from: 0, through:arregloEntradas.count - 1, by: 1){
    let arregloEntradasFinal = arregloEntradas[i].split(separator: ",")
    print(arregloEntradasFinal)
}

and I get the result of this:

this is the result

as you can see, the array elements are of string type, however I require them to be of Int type:

[1,1]
[1,3]
[4,1]
...

I hope you can help me, thank you in advance.

Upvotes: 0

Views: 295

Answers (3)

Hemang
Hemang

Reputation: 27050

What you're getting in arregloEntradasFinal is correct since you're processing the string array. Later, when you want to use arregloEntradasFinal again, you should again split a string by a comma separator from arregloEntradasFinal and use the individual Int value. For example:

let index = 0 // You can also loop through the array
let values = arregloEntradasFinal[index].split(separator: ",")
let num1 = Int(values.first ?? 0) // If no value then returns 0
let num2 = Int(values.last ?? 0)  // If no value then returns 0

Note - this is one of the way without using the map function.

Upvotes: 0

rmaddy
rmaddy

Reputation: 318804

Here's one approach using some splitting and mapping:

var cadenaCoordenadas = """
1,1
1,3
4,1
5,1
1,5
1,6
2,5
0,0
"""

let arregloEntradasFinal = cadenaCoordenadas.split(separator: "\n")
                           .map { $0.split(separator: ",").compactMap { Int($0) } }
print(arregloEntradasFinal)

Output:

[[1, 1], [1, 3], [4, 1], [5, 1], [1, 5], [1, 6], [2, 5], [0, 0]]

Upvotes: 1

arun siva
arun siva

Reputation: 869

var arregloEntradas = cadenaCoordenadas.split(separator: "\n")
print("primer Arreglo: ", arregloEntradas)
for i in stride(from: 0, through:arregloEntradas.count - 1, by: 1){
    let arregloEntradasFinal = arregloEntradas[i].split(separator: ",").map { Int(String($0)) }
    print(arregloEntradasFinal)
}

Upvotes: 0

Related Questions