gpt4 book ai didi

ios - 将列表的字符串转换为列表 Swift

转载 作者:行者123 更新时间:2023-11-28 12:34:51 24 4
gpt4 key购买 nike

有点卡在这里,假设我有一个变量,我们称它为 a,等于:

var a = "['Example 1', 'Example 2', 'Example3']"

如何将 a 转换为列表,以便可以使用 a[2] 访问它(例如)

//Make it so a is converted to a list, seeing as though it is a list, besides the two " on either side
var a = "['Example 1', 'Example 2', 'Example3']"
var b = ['Example 1', 'Example 2', 'Example3'] //<-- How can I get this?

我尝试过的:

var a = "['Example 1', 'Example 2', 'Example3']"
var b:Array = a // This did not work, hence this question.

提前致谢!

最佳答案

您的字符串不是我所知道的任何有效数据序列化格式。 (例如,它不完全是 JSON。)

没有直接的方法将该字符串转换为“列表”(数组?)

为此,您必须编写一堆字符串解析代码。

如果您使用双引号而不是单引号,它将是有效的 JSON,您可以使用 JSONSerialization 类将其转换为数组。

如果您使用 replaceOccurrencesOfString: "'", withString: "\"" 将单引号转换为双引号,那么您可以将结果字符串转换为数据,然后从那里转换为数组对象。

编辑:

在 Swift 3 中,从头到尾执行所有操作的代码如下所示:

var string = "['Example 1','Example 2','Example3']"

//Replace ` characters with "
string = string.replacingOccurrences(of: "'", with: "\"")

//Try to convert the string to Data using utf8 encoding
guard let data = string.data(using: .utf8) else {
fatalError()
}

let array = try! JSONSerialization.jsonObject(with: data, options: [])

print("array = \(array)")

注意上面我偷懒了。如果数据转换失败,我抛出一个 fatal error ,我使用try!形式的try,如果JSON转换失败,它会崩溃。在实际代码中,您希望对这两者进行错误恢复。

编辑#2:

在围绕 JSON 调用添加一个 try block 之后,将整个事情转换为一个函数,尝试将结果转换为一个字符串数组,并使用换行符加入结果数组,我们得到以下内容:

var string = "['Example 1','Example 2','Example3']"

func convertFunkyStringToStringArray(_ string: String) -> [String]? {

let adjustedString = string.replacingOccurrences(of: "'", with: "\"")
guard let data = adjustedString.data(using: .utf8) else {
return nil
}
do {
let result = try JSONSerialization.jsonObject(with: data, options: [])
return result as? [String]
} catch {
print("Error \(error) deserializing string as JSON")
return nil
}
}

if let array = convertFunkyStringToStringArray(string) {
let joinedString = array.joined(separator: "\n")
print("After conversion, array = \(array). Joined, result = \n\(joinedString)")
} else {
print("Unable to convert string to a [String] array")
}

如前所述,最好让原始字符串使用传统的序列化格式(如 JSON)。 (它几乎是 JSON。如果您只是使用双引号而不是单引号,它就是有效的 JSON。)

关于ios - 将列表的字符串转换为列表 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41173793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com