Convert a String to Array [Int] and vice versa

-1

Help me please!

  

STRING to ARRAY [Int]

input: var str = "4869"

output: var num:[Int] = [4,8,6,9]

  

ARRAY [Int] to STRING

input: var num2:[Int] = [5,8,9,6]

output: var str2 = "5896"

    
asked by Alberto Gw 13.05.2018 в 21:54
source

1 answer

1

Short version without explanation:

import UIKit

let str = "24234k234hj234"
var digits = str.flatMap({Int(String($0))})

print(digits)

print

[2, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4]

backwards

let numbers= [1,2,3] 
let text = numbers.map({String($0)}).joined()

print

"123"

Explanation

A string can be interpreted as an array of characters, so traverse it.

let str = "123456"
for char in str {

}

Now, each element is of type character , so you have to cast it, one way you could be:

Int(char)

But Int does not have a constructor with type character , so before you would have to pass it is chracter to string

String (char)

Then move it to Int

Int (String (char))

Yes, this constructor returns an optional so you should do an unwrapping.

Int (String (char))!

This, forced unwrapping is not recommended, so you could put it in a conditional, so you make sure you just take the numbers, here is a complete example

import UIKit

let str = "123123"
var digits: [Int] = []

for char in str {
    if let digit = Int(String(char)) {
        digits.append(digit)
    }
}

print(digits)

in this case prints

[1, 2, 3, 1, 2, 3]

another example, with letters in between

let str = "24234k234hj234"
...
print(str)

print

[2, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4]

map is a function that allows you to apply an action to each element of the array, flatMap ignores the nulls and delivers the version not optional

joined together the elements of an arrangement.

    
answered by 08.06.2018 в 22:49