Ich benutze Vapor für Swift Backend. Im Folgenden ist der Code, mit dem ich arbeite.Swift 3 optionale Zeichenfolge zu 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)!
Ich bin "id" als optionale Zeichenfolge für zB bekommen:? Optional ("123") für jsonContent .node.object [ "id"] ?. String
Wenn ich versuche, um es mit int (id) in int zu konvertieren! Ich bekomme zurück Null Wenn ich versuche zu tun, lassen Sie tempId = Int (id!) gibt es einen Fehler.
Aber wenn ich das gleiche im Spielplatz mache, bekomme ich richtigen int-Wert.
Warum optionale Zeichenfolge zu Int funktioniert nicht richtig in meiner Vapor-App? Irgendeine Idee.
Erste Vermutung ist, dass "ID" ist schon ein Int ... versuchen, nicht zu String an erster Stelle zu konvertieren? – brandonscript
Ersetzen Sie "let tempId = Int (id)!" Durch "let tempId = Int (id)". – shallowThought
Wie bekomme ich Int von Json Node-Objekt? denn wenn ich jsonContent node.object nenne? ["id"]? int gibt es nil und wenn ich jsonContent node.object nenne? ["id"]? dann wird es Node.Node-Objekt geben. – Tarang