[英]Compiling Swift source files hangs on large array reduce-combine + expressions
In my tests I'm used to write Strings in arrays in different lines like 在我的测试中,我习惯于在不同行的数组中编写字符串,例如
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: +)
That works fine, still my array get 145 lines for a large test json string. 效果很好,但我的数组仍可为大型测试json字符串获得145行。 With 145 lines (or maybe less, didn't tried it line by line) the build task hangs while "Compiling Swift source files".
145行(或者可能更少,没有逐行尝试)在“编译Swift源文件”时挂起了构建任务。
First, that is a bit crazy. 首先,这有点疯狂。 30 lines are ok, 145 not?
30行还可以,145行不行? What?
什么?
Second, what is a better solution to write a String in multiple lines in Swift? 其次,有什么更好的解决方案在Swift中以多行形式编写String? - I don't want to load a json and parse it from an external file.
-我不想加载json并从外部文件中解析它。
This is probably because of type inference. 这可能是因为类型推断。
Try giving an explicit [String] type to an array variable to help the compiler figure it out, then apply reduce to the variable. 尝试为数组变量赋予显式[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: +)
Anyway, to create JSON you should make a dictionary then serialize it with NSJSONSerialization, this is less error prone: 无论如何,要创建JSON,您应该制作一个字典,然后使用NSJSONSerialization对其进行序列化,这样不容易出错:
Swift 2 迅捷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)
}
Swift 3 迅捷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.