【问题标题】:Convert string representation of a nameless tuple, to tuple将无名元组的字符串表示形式转换为元组
【发布时间】:2016-12-20 04:56:11
【问题描述】:

我知道这可能很容易,但我对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: 中的 [] 更改为 (),但这不起作用。

【问题讨论】:

  • 您正在尝试从数组中创建一个元组?很难理解你需要什么
  • 我有一个字符串,如果没有第一个 " 和最后一个 ",它将是一个元组,但你不能通过简单的字符串替换来摆脱那些。我想改变"("Example 1", "Example 2")" -> ("Example 1", "Example 2")
  • 所以基本上你是想从一个字符串中创建一个元组? "("Example 1", "Example 2")" 到具有 "Example 1""Example 2" 的元组?
  • 字符串从何而来?为什么元组是这样存储的?单个字符串可以包含括号、逗号或引号吗?您是否考虑过使用不同的格式(如 JSON)?

标签: ios swift tuples


【解决方案1】:

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

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

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)

【讨论】:

  • 如果字符串本身包含括号或逗号怎么办? – 试试let string = "(\"A(B)C\", \"D, E\")"
  • 是的,这行得通,但是如果字符串包含逗号怎么办?
猜你喜欢
  • 2015-12-19
  • 1970-01-01
  • 2019-12-03
  • 1970-01-01
  • 2017-04-30
  • 2016-03-14
  • 2023-03-03
  • 2021-02-20
  • 2012-01-27
相关资源
最近更新 更多