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

时间:2016-12-20 04:56:12

标签: ios swift tuples

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

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

现在我想知道是否有办法转换为tuple,可能还有JSONSerialization

我试过了 let array = try! JSONSerialization.jsonObject(with: data, options: []) as! Array<Any>,和使用"["Example 1", "Example 2"]"字符串,但不是元组,我尝试将[]中的options:更改为(),但那没用。

1 个答案:

答案 0 :(得分: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])
}

那么你可以像这样使用它

let string = "(\"Example 1\", \"Example 2\")"
let result = extractTuple(string)
print(result)
相关问题