Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string representation of a nameless tuple, to tuple

Tags:

ios

swift

tuples

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.

like image 762
Will Avatar asked Dec 20 '16 04:12

Will


People also ask

How do you convert a string to a tuple?

Method #1 : Using map() + int + split() + tuple() This method can be used to solve this particular task. In this, we just split each element of string and convert to list and then we convert the list to resultant tuple.

How do you convert a tuple to a tuple?

Tuple String to a Tuple Using The eval() Function in Python The eval() function is used to evaluate expressions. It takes a string as an input argument, traverses the string, and returns the output. We can directly convert the tuple string to a tuple using the eval() function as shown below.

Which function converts string to tuple in Python?

Python's built-in function tuple() converts any sequence object to tuple. If it is a string, each character is treated as a string and inserted in tuple separated by commas.


1 Answers

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)
like image 63
Mohammadalijf Avatar answered Nov 15 '22 05:11

Mohammadalijf