简体   繁体   中英

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:

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

How can I convert a to list, so it can be accessed with a[2] (for example)

//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.)

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.

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.

EDIT:

The code to do everything beginning to end looks like this in 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! form of try, which will crash if the JSON conversion fails. In real code you'd want error recovery on both of those.

EDIT #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:

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. (It is almost JSON. If you just used double quotes rather than single quotes, it would be valid JSON.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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