Swift 3可选字符串为int

时间:2017-01-23 18:49:20

标签: ios swift optional

我正在使用Vapor for Swift后端。以下是我正在使用的代码。

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的可选(“123”)。。node.object?[“id”]?。string

当我尝试使用Int(id)将其转换为int时!我回来了 如果我尝试让tempId = Int(id!)则会出错。

但是当我在游乐场做同样的事情时,我得到了正确的int值。

let id: String?

id = "1234"

let myInt = Int(id!)

为什么在我的Vapor应用程序中,Int的可选字符串无法正常工作? 任何的想法。

3 个答案:

答案 0 :(得分:1)

如果" id"是一个可选的字符串,那么你可能不想用#34;!"强行展开它。

最安全的方法是:

Sub RemoveRowsAndFormat()  
 Dim WS As Worksheet
 For Each WS In Sheets
 WS.Activate


   Dim n As Long
     Dim nlast As Long
     Dim rw As Range
     Set rw = ActiveWorkbook.ActiveSheet.UsedRange.Rows
     nlast = rw.Count
     For n = nlast To 9 Step -1
      If (rw.Cells(n, 3).Value = "Contributions-All Other" Or rw.Cells(n, 3).Value = "Program Fees - Youth" Or rw.Cells(n, 3).Value = "Financial Assitance" Or rw.Cells(n, 3).Value = "Salaries & Wages" Or rw.Cells(n, 3).Value = "Payroll Taxes" Or rw.Cells(n, 3).Value = "Employee Benefits" Or rw.Cells(n, 3).Value = "Staff Training and Confer." Or rw.Cells(n, 3).Value = "Occupancy" Or rw.Cells(n, 3).Value = "Supplies" Or rw.Cells(n, 3).Value = "Telephone" Or rw.Cells(n, 3).Value = "Postage & Shipping" Or rw.Cells(n, 3).Value = "Promotion and Advertising" Or rw.Cells(n, 3).Value = "Bad Debt" Or rw.Cells(n, 3).Value = "Program Operating Expense" Or rw.Cells(n, 3).Value = "Program Operating Net") Then
      rw.Rows(n).EntireRow.Insert
        ElseIf (rw.Cells(n, 4).Value = "" And rw.Cells(n, 5).Value = "" And rw.Cells(n, 6).Value = "" And rw.Cells(n, 7).Value = "" And rw.Cells(n, 8).Value = "" And rw.Cells(n, 9).Value = "" And rw.Cells(n, 10).Value = "" And rw.Cells(n, 11).Value = "") Then
             rw.Rows(n).Delete


         End If

     Next n
     Next WS
 End Sub

它"工作的原因"在操场上,你肯定是给字符串赋予一个非零值(因此你可以解除力量)。

答案 1 :(得分:1)

字符串!
可能包含字符串,或者可能包含nil。它就像一个常规可选项,但Swift允许您直接访问该值而无需展开安全性。如果你尝试这样做,就意味着你知道那里有一个价值 - 但如果你错了,你的应用就会崩溃

var optionalString: String? = "123"

// first check if it doesn't contain nil
if let str = optionalString {
    // string to -> Int
    if let id = Int(str) {
        print(id) // work with id
    }
} else {
    // optionalString contains nil
}

答案 2 :(得分:1)

我发现在我的iOS代码中我有一个struct带有可选属性coz,当映射到Dict时,它给对象提供了键的可选值。

如果我将属性设置为非可选属性,并在其工作正常后将其发送到蒸汽后端。

所以基本上是正确使用Optionals的情况。

相关问题