Will
Will

Reputation: 5490

Convert string representation of a nameless tuple, to tuple

I know this might be easy, but I am very new to Swift and need all the help I can get.

I have a string that when printed shows, "("Example 1", "Example 2")"
Now if I assign that to a variable, I can't call individual elements in the tuple, as it is clearly not a tuple.

Now I would like to know if there is a way to convert into a tuple, perhaps with JSONSerialization?

I tried let array = try! JSONSerialization.jsonObject(with: data, options: []) as! Array<Any>,
and that works with a string of "["Example 1", "Example 2"]", but not a tuple, I tried changing the [] in options: to (), but that did not work.

Upvotes: 8

Views: 1414

Answers (1)

Mohammadalijf
Mohammadalijf

Reputation: 1377

base on what i understand you want to create a tuple out of a string, which the string looks kinda like a tuple as well. so what you need to do is extract values within this string and create a tuple.

here is simple solution if you are always sure the format is the same

func extractTuple(_ string: String) -> (String,String) {
     //removes " and ( and ) from the string to create "Example 1, Example 2"
    let pureValue = string.replacingOccurrences(of: "\"", with: "", options: .caseInsensitive, range: nil).replacingOccurrences(of: "(", with: "", options: .caseInsensitive, range: nil).replacingOccurrences(of: ")", with: "", options: .caseInsensitive, range: nil)

    let array = pureValue.components(separatedBy: ", ")
    return (array[0], array[1])
}

then you can use it like this

let string = "(\"Example 1\", \"Example 2\")"
let result = extractTuple(string)
print(result)

Upvotes: 4

Related Questions