我知道这可能很容易,但我对 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:
至 ()
,但这没有用。
最佳答案
根据我的理解,您想从字符串中创建一个元组,该字符串看起来也有点像元组。所以您需要做的是提取此字符串中的值并创建一个元组。
如果您始终确定格式相同,这里有一个简单的解决方案
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)
关于ios - 将无名元组的字符串表示形式转换为元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41235147/