0

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.

1
  • Unrelated: for i in stride(from: 0, through:arregloEntradas.count - 1, by: 1) is a bad way of saying for i in stride(from: 0, to: arregloEntradas.count, by: +1), which is a really complicated way of saying for i in 0..<arregloEntradas.count, which is a really error prone way of saying for i in arregloEntradas.indices. But you don't even need the index, you need the element, so it could just be for arregloEntradasFinal in arregloEntradas. Commented Jun 7, 2019 at 5:13

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.