简体   繁体   English

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

[英]Convert a string of a list to a list Swift

Little stuck here, let's say I have a variable, we'll call it a, equal to: 有点卡在这里,假设我有一个变量,我们称它为a,等于:

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

How can I convert a to list, so it can be accessed with a[2] (for example) 如何将a转换为list,以便可以使用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?

What I've tried: 我试过的

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

Thanks in advance! 提前致谢!

You have a string that is not in any valid data serialization format I am aware of. 您所知道的字符串不是任何有效的数据序列化格式。 (It's not quite JSON, for example.) (例如,它不是完全JSON)。

There is no straightforward way to convert that string to a "list" (array?) 没有直接的方法将该字符串转换为“列表”(数组?)。

You would have to write a bunch of string parsing code to do so. 为此,您必须编写一堆字符串解析代码。

If you used double quotes rather than single quotes it would be valid JSON and you could use the JSONSerialization class to convert it to an array. 如果使用双引号而不是单引号,则它将是有效的JSON,并且可以使用JSONSerialization类将其转换为数组。

If you used replaceOccurrencesOfString: "'", withString: "\\"" to convert the single-quotes to double quotes then you could convert the resulting string to Data, and from there to an Array object. 如果使用replaceOccurrencesOfString: "'", withString: "\\""将单引号转换为双引号,则可以将结果字符串转换为Data,然后从该字符串转换为Array对象。

EDIT: 编辑:

The code to do everything beginning to end looks like this in Swift 3: 在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)")

Note that I was lazy above. 注意上面我很懒。 If the data conversion fails, I throw a fatal error, and I use the try! 如果数据转换失败,则抛出致命错误,然后try!使用try! form of try, which will crash if the JSON conversion fails. 尝试形式,如果JSON转换失败,它将崩溃。 In real code you'd want error recovery on both of those. 在真实代码中,您都希望对两者都进行错误恢复。

EDIT #2: 编辑#2:

After adding a try block around the JSON call, converting the whole thing to a function, trying to cast the results to an array of strings, and joining the resulting array using linefeeds, we get the following: 在围绕JSON调用添加try块,将整个对象转换为函数,尝试将结果转换为字符串数组并使用换行符将结果数组连接起来之后,我们得到以下信息:

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")
}

As discussed, you'd be much better off making your original string use a conventional serialization format like JSON. 如前所述,最好让原始字符串使用JSON之类的常规序列化格式。 (It is almost JSON. If you just used double quotes rather than single quotes, it would be valid JSON.) (它几乎是JSON。如果仅使用双引号而不是单引号,则它将是有效的JSON。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM