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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With