下面的代码我正在将字符串转换为字典,但无法正常工作。
let body = "{status:0}"
do {
let dictionary = try convertToDictionary(from: body ?? "")
print(dictionary) // prints: ["City": "Paris"]
} catch {
print(error)
}
func convertToDictionary(from text: String) throws -> [String: String] {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String] ?? [:]
}
该值为Int
,所以类型转换为[String:String]
失败。
这与any
值类型一起使用
let body = "{status:0}"
do {
let dictionary = try convertToDictionary(from: body)
print(dictionary) // prints: ["City": "Paris"]
} catch {
print(error)
}
func convertToDictionary(from text: String) throws -> [String: Any] {
let data = Data(text.utf8)
return try JSONSerialization.jsonObject(with: data) as? [String:Any] ?? [:]
}