簡體   English   中英

編譯Swift源文件掛在大型數組reduce-combine +表達式上

[英]Compiling Swift source files hangs on large array reduce-combine + expressions

在我的測試中,我習慣於在不同行的數組中編寫字符串,例如

    let jsonString = ["{"
        ,"\"url\": \"http://localhost:8090/rest/api/3\","
        , "\"id\": \"3\","
        , "\"description\": \"A test that needs to be done.\","
        , "\"name\": \"Test\","
        , "\"subtest\": false,"
        , "\"avatar\": 1"
        ,"}"].reduce("", combine: +)

效果很好,但我的數組仍可為大型測試json字符串獲得145行。 145行(或者可能更少,沒有逐行嘗試)在“編譯Swift源文件”時掛起了構建任務。

首先,這有點瘋狂。 30行還可以,145行不行? 什么?

其次,有什么更好的解決方案在Swift中以多行形式編寫String? -我不想加載json並從外部文件中解析它。

這可能是因為類型推斷。

嘗試為數組變量賦予顯式[String]類型,以幫助編譯器解決該問題,然后將reduce應用於該變量。

let arrayOfStrings: [String] = ["{"
    ,"\"url\": \"http://localhost:8090/rest/api/3\","
    , "\"id\": \"3\","
    , "\"description\": \"A test that needs to be done.\","
    , "\"name\": \"Test\","
    , "\"subtest\": false,"
    , "\"avatar\": 1"
    ,"}"] // etc

let jsonString = arrayOfStrings.reduce("", combine: +)

無論如何,要創建JSON,您應該制作一個字典,然后使用NSJSONSerialization對其進行序列化,這樣不容易出錯:

迅捷2

do {
    // Create a dictionary.
    let dict = ["url": "http://localhost:8090/rest/api/3", "id": "3"]  // etc

    // Encode it to JSON data.
    let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: [])

    // Get the object back.
    if let jsonObject = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? [String:String] {
        print(jsonObject)
    }

    // Get it as a String.
    if let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding) {
        print(jsonString)
    }

} catch let error as NSError {
    print(error)
}

迅捷3

do {
    // Create a dictionary.
    let dict = ["url": "http://localhost:8090/rest/api/3", "id": "3"]  // etc

    // Encode it to JSON data.
    let jsonData = try JSONSerialization.data(withJSONObject: dict, options: [])

    // Get the object back.
    if let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String:String] {
        print(jsonObject)
    }

    // Get it as a String.
    if let jsonString = String(data: jsonData, encoding: String.Encoding.utf8) {
        print(jsonString)
    }

} catch let error as NSError {
    print(error)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM