-4

Is there any simple method to convert string that looks like that: [[1,2],[1,3],[1,4]] to array with arrays?

I will be glad.

3
  • 3
    That does not look like the description of a dictionary. How did you obtain the string? – Better choose a format like JSON if you have to convert dictionaries/arrays to a string and back. Commented Feb 22, 2017 at 20:43
  • Sorry for mistake, I thought about Array... Commented Feb 22, 2017 at 20:54
  • 1
    Possible duplicate of stackoverflow.com/questions/37391290/… Commented Feb 22, 2017 at 21:22

2 Answers 2

1

The easiest option is to convert it to JSON and back:

let str = "[[1,2],[1,3],[1,4]]"
let data = str.data(using: .utf8)!

do {
    let json = try JSONSerialization.jsonObject(with: data, options: [])
    if let arr = json as? [[Int]] {
        print(arr)
    }
} catch {
    print(error)
}
Sign up to request clarification or add additional context in comments.

Comments

0

I made that method for it and it works:

func convertToArray(string: String) -> [[Int]] {
    var arrayOrder = 0
    var mainArray: [[Int]] = []
    var array: [Int] = []

    for character in string.characters {
        if character == "[" {
            arrayOrder += 1
        }

        if arrayOrder >= 2 && character != "[" && character != "]" && character != "," {
            let integer: Int = Int(String(character))!
            array.append(integer)
        }

        if character == "]" {
            if arrayOrder >= 2 {
                mainArray.append(array)
                array = []
            }

            arrayOrder -= 1
        }
    }

    return mainArray
}

1 Comment

It is only if we have one level of arrays in main array.

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.