[[+content_image]]
A
A
andrey_kino2017-11-19 17:01:21
Swift
andrey_kino, 2017-11-19 17:01:21

How to turn a String array into an Int array (multidimensional)?

There is an array

[["9", "6", "7", "8", "5"], ["1", "1", "1", "1", "1"]]
, you need to get a new one
I do and I get an error
let arr = [["9", "6", "7", "8", "5"], ["1", "1", "1", "1", "1"]]
let mapArr = arr.map{Int($0).map{Int($0)}}

although the design itself is working and gives a result
let arr = [[1,2,3],[4,5,6]]
let mapArr = arr.map{$0.map{$0 * 2}}
mapArr // [[2, 4, 6], [8, 10, 12]]

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Globak, 2017-11-20
@andrey_kino

Good afternoon!
In your first example, you are trying to convert an array of strings to Int and you are getting an error.
If you use .map, then it returns an array of optional values. And in this case, if there is a string in the array that cannot be converted to Int, then there will be nil in this place.
If you use flatMap , then it will leave only those values ​​​​that were successfully converted to Int.

let arr = [["9", "6", "7", "8", "5"], ["1", "1", "1", "1", "1"]]
let mapArr = arr.flatMap { $0.flatMap { Int($0) } }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question