2015-12-03 102 views
0

這應該是簡單明瞭,但嘗試趕上swift2挫敗我。這是我的代碼。嘗試趕不上工作在迅速

@IBAction func btnAdd_TouchDown(sender: AnyObject) { 

     do { try AddNewNotesToList() } catch{ 

      if(Ex.UnknownError != "") 
      { 
       Error(Ex.UnknownError) 
      } 
     } 
    } 



func AddNewNotesToList() throws 
    { 
     var obj: TreatmentNotesDTO = TreatmentNotesDTO() 
     obj.therapist_id = Int(TherapistId)! // getting error here 
     return 
    } 

錯誤:

fatal error: unexpectedly found nil while unwrapping an Optional value

調試器應該去追趕,但其分手。我來自c#,剛開始swift2。任何幫助

+0

要發現錯誤,目標函數必須拋出一個錯誤。請閱讀語言指南中的「錯誤處理」一章:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42- ID508 – vadian

+0

沒有得到你,任何代碼,你可以顯示? –

+0

我在函數中添加了'throws',但仍然無法正常工作。我不想手動定義錯誤。 Swift應該自動選擇像c#,javascript等語言的錯誤。 –

回答

1

我會建議你使用guard趕上這樣的錯誤:

guard let therapistID = Int(TherapistId) else { 
    print(TherapistId + " cannot be converted to an Int") 
    return 
    // or mark function as throws and return an error 
    throw NSError(domain: TherapistId + " cannot be converted to an Int", code: 0, userInfo: nil) 
} 
obj.therapist_id = therapistID 

注意Int(TherapistId)!throws拋出一個錯誤。它是一個fatal error它停止程序執行。