0

say I have a variable

let stringArray = "[\"You\", \"Shall\", \"Not\", \"PASS!\"]"

// if I show this, it would look like this
print(stringArray)
["You", "Shall", "Not", "PASS!"]

now let's have an Array< String>

let array = ["You", "Shall", "Not", "PASS!"]

// if I convert this into string
// it would roughly be equal to the variable 'stringArray'

if String(array) == stringArray { 
    print("true")
} else {
    print("false")
}

// output would be
true

now say what should I do to convert variable 'stringArray' to 'Array< String>'

8
  • This question shows that there is no eval operation in Swift, so you could write a little parser. Commented Nov 28, 2016 at 10:41
  • 3
    This is JSON. Use the (NS)JSONSerialization class. Commented Nov 28, 2016 at 10:43
  • so I'd have to regex the hell out of it? that's the only way I'm thinking of doing this right now.. sadly Commented Nov 28, 2016 at 10:44
  • @vadian no this isn't JSON because JSON is [key:value, key:value] whereas this is just [value, value, value] or am I wrong? Commented Nov 28, 2016 at 10:45
  • 3
    Believe me, it is JSON. Commented Nov 28, 2016 at 10:46

2 Answers 2

1

The answer would be to convert the string using NSJSONSerialization

Thanks Vadian for that tip

let dataString = stringArray.dataUsingEncoding(NSUTF8StringEncoding)
let newArray = try! NSJSONSerialization.JSONObjectWithData(dataString!, options: []) as! Array<String>

for string in newArray {
    print(string)
}

voila there you have it, it's now an array of strings

Sign up to request clarification or add additional context in comments.

4 Comments

mutableContainers is completely useless in Swift, only to read the data it's not needed anyway.
@AhmadF I should wait for 2 days to accept my own answer
@vadian what would be the best option to use then? (optimization wise)
No options ([]).
0

A small improvement for Swift 4.

Try this:

// Array of Strings
let array: [String] = ["red", "green", "blue"]
let arrayAsString: String = array.description
let stringAsData = arrayAsString.data(using: String.Encoding.utf16)
let arrayBack: [String] = try! JSONDecoder().decode([String].self, from: stringAsData!)

For other data types respectively:

// Set of Doubles
let set: Set<Double> = [1, 2.0, 3]
let setAsString: String = set.description
let setStringAsData = setAsString.data(using: String.Encoding.utf16)
let setBack: Set<Double> = try! JSONDecoder().decode(Set<Double>.self, from: setStringAsData!)

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.