我的代码之前支持Swift 3.3,现在我使用Xcode 9.3将其升级到Swift 4.1。它在尝试构建项目时向我显示以下错误。
以下是JSON解析的代码
// MARK: Store JSON initializer
convenience init?(withJSON json: JSON) {
//json mapping
//This is of type [Character] after mapping
let services = json["services"].arrayValue.flatMap({ $0 }).flatMap({ $0.1.stringValue }) //Convert response to 1D array and convert it to array if String
}
这是我尝试调用
的init方法//Custom init method
init(id: Int, storeNumber: String, title: String, location: Location, type: String, zip: String, parent: Int, city: String, services: [String], state: String, storePhone: [String], pharmacyPhone: [String], pharmacyFax: [String], workingHours: WorkingHoursString) {
//field with error
//here self.services is of type [String]
self.services = services
}
我正在使用 pod' SwiftyJSON',' 3.1.4' 用于Json解析。
错误 - 无法转换类型' [字符]'的值预期的论点 键入' [String]'
/* JSON for services is as given
"services":[
[
"Fresh Food"
]
]
*/
print("Services are \(services)")
Services are ["F", "r", "e", "s", "h", " ", "F", "o", "o", "d"]
解决这个问题的最简单的解决办法是什么?
答案 0 :(得分:2)
在以下代码中可以观察到相同的行为:
let services: [[String: Any]?] = [
["service1": "service1-name"],
["service2": "service2-name"]
]
let result = services
.flatMap({ $0 })
.flatMap({ $0.1 as! String })
print(result)
我认为这是由Swift 4中String
和Dictionary
的多项更改引起的(例如,String
成为Collection
个字符。在上面的代码中,第一个flatMap
将字典合并(展平)为一个字典,第二个flatMap
将每个值作为String
并将它们展平为2D Collection
Character
。
我想你想要这样的东西:
let result = services
.compactMap { $0 } // remove nil dictionaries
.flatMap { // take all dictionary values as strings and flatten them to an array
$0.values.map { $0.stringValue }
}
print(result)
此行给出一个字符串数组,预期结果
let services = json["services"]
.arrayValue
.flatMap { $0.arrayValue }
.map { $0.stringValue }