我正在使用Vapor作为Swift后端。以下是我正在使用的代码。Swift 3可选字符串到int
drop.post("postTodo") { request in
var jsonContent: JSON?
if let contentType = request.headers["Content-Type"], contentType.contains("application/json"), let jsonData = request.json {
jsonContent = jsonData
print("Got JSON: \(jsonContent)")
}
guard let id = jsonContent?.node.object?["id"]?.string
else {
return JSON(["message": "Please include mandatory parameters"])
}
let tempId = Int(id)!
我收到 “ID”,作为如可选字符串:??可选的jsonContent .node.object( “123”)[ “ID”] ?.串
当我尝试使用Int(id)将其转换为int!我回来零 如果我尝试让tempId = Int(id!)它会给出错误。
但是当我在操场上做同样的事情时,我得到了正确的int值。
let id: String?
id = "1234"
let myInt = Int(id!)
为什么可选字符串到Int在我的Vapor应用程序中无法正常工作? 任何想法。
第一个猜测是'id'已经是一个Int ...尝试不首先转换为字符串? – brandonscript
用'let tempId = Int(id)'替换'let tempId = Int(id)!'。 – shallowThought
那么我如何从json节点对象获取int?因为如果我调用jsonContent?.node.object?[“id”]?。int它会给零,如果我打电话给jsonContent?.node.object?[“id”]?那么它会给Node.Node对象。 – Tarang