使用Swift 3.0将包含"Array of String"的String解析为Array

Edw*_*ony 0 swift

我正在寻找一种使用Swift 3.0将此字符串转换为数组的方法

let arrayString: String = "[\"One\", \"Two\", \"Three\", \"Four\"]"

// Should be converted into:

let array: [String] = [
    "One",
    "Two",
    "Three",
    "Four"
]
Run Code Online (Sandbox Code Playgroud)

如果我使用它,作为分隔符将它分成令牌,它将包括[,]因此它将无法工作.如何正确转换?

注意:

问题不同于: 在Swift中将JSON字符串转换为Object的简单而干净的方法

我不是要尝试转换其中包含多个键的JSON对象.

Uje*_*esh 7

它是一个JSON字符串,你必须使用JSONSerialization在普通字符串数组中转换它.

Swift 3.0

func convertToArray(str: String) -> [String]? {

    let data = str.data(using: .utf8)

    do {
        return try JSONSerialization.jsonObject(with: data!, options: []) as? [String]
    } catch {
        print(error.localizedDescription)
    }

   return nil

 }

let aString: String = "[\"One\", \"Two\", \"Three\", \"Four\"]"

let arrayString = convertToArray(str: aString)

print(arrayString) // ["One", "Two", "Three", "Four"]
Run Code Online (Sandbox Code Playgroud)