简体   繁体   中英

How to convert string containing array to array in Swift?

I have a string in Swift that contains an array in it. Is it possible to convert the string into an array? All I have found on the internet is converting "abc" to ["a","b","c"] , which I would like to do. 这样做。

String: "[\\"value1\\",\\"value2\\",\\"value3\\"]"
Result: ["value1","value2","value3"]

I am getting the string from a web request. The code for the request is here:

func webRequest(uri:String)->String{
        var value = "";
        let request = URLRequest(url: NSURL(string: uri)! as URL)
        do {
            let response: AutoreleasingUnsafeMutablePointer<URLResponse?>? = nil
            let data = try NSURLConnection.sendSynchronousRequest(request, returning: response)
            value = String(data: data, encoding: .utf8)!;
        } catch _ {

        }
        return value;
}

First off, the problem here is not converting your string into an array. The problem is getting the array from the web request in the first place.

Let me update your web request function.

func webRequest(url: URL, completion: ([String]?) -> () { // I have updated this function to be asynchronous
    let dataTask = URLSession.shared.dataTask(with: url) {
        data, urlResponse, error in

        // you might want to add more code in here to check the data is valid etc...

        guard let data = data,
              let arrayOfStrings = JSONDecoder().decode([String].self, from: data) else {
            // something went wrong getting the array of strings so return nil here...
            completion(nil)
            return
        }

        completion(arrayOfStrings)
    }

    dataTask.resume()
}

Using this code instead of the code in your question you now have an asynchronous function that will not block the app and one that will pass your array of strings into the completion.

You can now run it like this...

webRequest(url: someURL) { strings in
    guard let strings = strings else {
        // strings is nil because something went wrong with the web request
        return
    }

    print(strings)
}

Creating the URL

In your question you have this code... NSURL(string: someString)! as URL NSURL(string: someString)! as URL

You can change this to... let url = URL(string: someString)

Quick side note

Careful where you find tutorials and using code you find on the web. The code used in this question is very old. (at least 4 or 5 years "out of date").

If you're looking for tutorials to help with Swift then some recommendations are...

I changed the string array to this:

{
    "response" : ["a","b","c"]
}

I then used JSONDecoder() to get the array:

func jsonDecode(jsonString:String)->Response{
    let jsonData = jsonString.data(using: .utf8)!
    let decoder = JSONDecoder()
    let decoded = try! decoder.decode(Response.self, from: jsonData)
    return decoded;
}
struct Response: Codable {
    let response: [String]
}

To retrieve array: jsonDecode(...).response

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