【问题标题】:How to convert string containing array to array in Swift?如何在 Swift 中将包含数组的字符串转换为数组?
【发布时间】:2019-06-09 17:23:46
【问题描述】:

我在 Swift 中有一个字符串,其中包含一个数组。是否可以将字符串转换为数组?我在互联网上发现的只是将"abc" 转换为["a","b","c"],这是我愿意这样做的。

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

我正在从网络请求中获取字符串。请求的代码在这里:

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;
}

【问题讨论】:

  • 你从哪里得到字符串?您能否首先显示如何获取字符串的代码?这会有所帮助????????
  • "我在 Swift 中有一个字符串,其中包含一个数组。"不,你没有,不是真的。您有多个项目的文本表示,但它既不是有效的 Swift,也不是有效的 JOSN(因为单引号)
  • 这就是我们所说的 XY 问题 :-)
  • 这个 is JSON 很可能(反斜杠是打印字符串的产物)。
  • 好的。感谢您添加该代码。我猜你是从教程或其他东西中得到这个的,因为这是非常古老的代码。 NSURLConnection 至少有 4 或 5 年没有成为首选的网络类。让我为你写一个答案来更新你的代码。

标签: arrays swift string


【解决方案1】:

首先,这里的问题是没有将您的字符串转换为数组。问题首先是从 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()
}

使用此代码而不是您问题中的代码,您现在拥有一个不会阻塞应用程序的异步函数,以及一个将您的字符串数组传递给完成的函数。

您现在可以像这样运行它...

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

    print(strings)
}

创建网址

在您的问题中,您有此代码...NSURL(string: someString)! as URL

您可以将其更改为... let url = URL(string: someString)

快速附注

小心在哪里找到教程和使用在网络上找到的代码。这个问题中使用的代码非常古老。 (至少 4 或 5 年“过时”)。

如果您正在寻找帮助 Swift 的教程,那么一些建议是...

【讨论】:

    猜你喜欢
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 2014-11-07
    • 2015-09-09
    相关资源
    最近更新 更多