How can I get from the text taped in text Field an Array of type: [String], or even better-[Int64] or [Int]?
You mean put the value of a text field into an array?
No. I mean to get an array from the Symbols typed into a text field. For example: If in a text field typed this- “20 30 40 50 60” I need to get an Array [20, 30, 40, 50, 60]
In order to do that you will have to get the string that the user typed in and then convert it into an array.
Here is an example from Playground
let char = "10 20 30 40 50 60 70 80 90"
let stringArray: [String] = char.components(separatedBy: " ")
let integerArray = stringArray.map { Int($0)!}
print(integerArray)
The result is:
[10, 20, 30, 40, 50, 60, 70, 80, 90]
It would be better to use compactMap
to convert the values from String
to Int
in case the user typed in something that can’t be cast to an Int
. That would result in a nil
value, which means you would need an array of Optional Int
. Or use compactMap
to filter out all the nil
values. And then you don’t need to force unwrap the casting result.
So, like this:
let integerArray = stringArray.compactMap { Int($0) }
Good suggestion Patrick.
Cheers
This works nicely when you mix up the numbers and have the result sorted too.
let char = "20 10 40 60 50 70 80 30 90 A ^ <"
let stringArray: [String] = char.components(separatedBy: " ")
let integerArray = stringArray.compactMap { Int($0) }.sorted()
print(integerArray)
Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90]