将无名元组的字符串表示形式转换为元组

Wil*_*ill 8 tuples ios swift

我知道这可能很容易,但我很新,Swift并且需要我能得到的所有帮助.

我有一个字符串,当打印显示时,"("Example 1", "Example 2")"
现在,如果我将其分配给变量,我不能调用中的单个元素tuple,因为它显然不是tuple.

现在我想知道是否有办法转换成一个tuple,也许有JSONSerialization

我尝试了 let array = try! JSONSerialization.jsonObject(with: data, options: []) as! Array<Any>,
并且使用了一串"["Example 1", "Example 2"]",但不是一个元组,我尝试将[]in 更改options:(),但这不起作用.

Moh*_*ijf 4

根据我的理解,您想从字符串创建一个元组,该字符串看起来也有点像元组。所以您需要做的是提取该字符串中的值并创建一个元组。

如果您始终确定格式相同,这是简单的解决方案

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])
}
Run Code Online (Sandbox Code Playgroud)

那么你可以像这样使用它

let string = "(\"Example 1\", \"Example 2\")"
let result = extractTuple(string)
print(result)
Run Code Online (Sandbox Code Playgroud)