Zonily Jame
Zonily Jame

Reputation: 5359

Convert Array<String> to String then back to Array<String>

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>'

Upvotes: 0

Views: 714

Answers (2)

Alexey Chekanov
Alexey Chekanov

Reputation: 1117

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!)

Upvotes: 0

Zonily Jame
Zonily Jame

Reputation: 5359

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

Upvotes: 1

Related Questions