简体   繁体   English

如何在Swift中将包含数组的字符串转换为数组?

[英]How to convert string containing array to array in Swift?

I have a string in Swift that contains an array in it. 我在Swift中有一个字符串,其中包含一个数组。 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 not like to do. 我在互联网上找到的所有内容都将"abc"转换为["a","b","c"] ,我不想这样做。

String: "[\\"value1\\",\\"value2\\",\\"value3\\"]" 字符串: "[\\"value1\\",\\"value2\\",\\"value3\\"]"
Result: ["value1","value2","value3"] 结果: ["value1","value2","value3"]

I am getting the string from a web request. 我正在从Web请求获取字符串。 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. 问题首先是从Web请求获取数组。

Let me update your web request function. 让我更新您的Web请求功能。

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 创建URL

In your question you have this code... NSURL(string: someString)! as URL 在您的问题中,您有以下代码... NSURL(string: someString)! as URL NSURL(string: someString)! as URL

You can change this to... let url = URL(string: someString) 您可以将其更改为... 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"). (“过期”至少4或5年)。

If you're looking for tutorials to help with Swift then some recommendations are... 如果您正在寻找可以帮助Swift的教程,那么一些建议是...

I changed the string array to this: 我将字符串数组更改为:

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

I then used JSONDecoder() to get the array: 然后,我使用JSONDecoder()获取数组:

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 检索数组: jsonDecode(...).response

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

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