0
["[\"1\", \"7\", \"13\", \"19\", \"25\"]", "[\"6\", \"12\", \"13\"]"]

I am getting this as output how to get string array like this in Swift

["1", "7", "13", "19", "25", "6", "12", "13"]

I tried all to convert this array in proper array but no luck. Is there a solution for this ?

Thank You!!

5
  • what is your trying sofar? Commented Jun 23, 2017 at 19:13
  • @Pratik Sanap you need to remove or replace occurrence of "\" before appending to array. Commented Jun 23, 2017 at 19:15
  • Edit your question to include the code you used to create the array. Commented Jun 23, 2017 at 19:16
  • there was optional string present in array I removed that. and also I tried to replace "\" with " " but no luck Commented Jun 23, 2017 at 19:17
  • thank you guys for your time! Commented Jun 23, 2017 at 19:30

2 Answers 2

1

Simple solution (without significant error handling), the strings can be treated as JSON

let array = ["[\"1\", \"7\", \"13\", \"19\", \"25\"]", "[\"6\", \"12\", \"13\"]"]

var result = [String]()
for item in array {
    let jsonArray = try! JSONSerialization.jsonObject(with: item.data(using: .utf8)!) as! [String]
    result.append(contentsOf: jsonArray)
}
print(result)
Sign up to request clarification or add additional context in comments.

1 Comment

Or let result = array.flatMap { try! JSONSerialization.jsonObject(with: $0.data(using: .utf8)!) as! [String] }
1

First, assuming you had a simple array of arrays, you can flatten it with flatMap:

let input = [["1", "7", "13", "19", "25"], ["6", "12", "13"]]
let output = input.flatMap { $0 }

That outputs

["1", "7", "13", "19", "25", "6", "12", "13"]

Or, even easier, just append the second array to the first one, bypassing the array of arrays altogether:

let array1 = ["1", "7", "13", "19", "25"]
let array2 = ["6", "12", "13"]
let output = array1 + array2

But your example looks like it's not an array of arrays, but rather array of descriptions of arrays, e.g. something like:

let array1 = ["1", "7", "13", "19", "25"]
let array2 = ["6", "12", "13"]
let input = ["\(array1)", "\(array2)"]

let output = ...                       // this is so complicated, I wouldn't bother trying it

Rather than figuring out how to reverse this array of interpolated strings, I'd suggest you revisit how you built that, bypassing interpolated strings (or description of the arrays).

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.