2015-08-28 69 views
0

我想探索這個新的(對我)的語言,和我做的是和許多人一樣,從服務器獲取一些JSON數據的應用程序。 在此功能(從教程中,我發現)我得到的4個錯誤,我無法修復:錯誤在做catch語句中迅速

func json_parseData(data: NSData) -> NSDictionary? { 
    do { 
    let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) 
    print("[JSON] OK!") 
    return (json as? NSDictionary) 
    }catch _ { 
     print("[ERROR] An error has happened with parsing of json data") 
     return nil 

    } 
} 

第一個是在「嘗試」,Xcode的建議我使用來解決它「嘗試;」 別人在「捕獲」和此人:

  • 支護語句塊是未使用的封閉
  • 類型的表達式是模糊的沒有更多的情況下
  • 預期,而在DO-while循環

請幫我瞭解

+2

我假設你使用SWIFT 2.0嗎? – Swinny89

+0

您使用Xcode中6,但斯威夫特2只在Xcode 7 – Moritz

回答

0

看來你正在使用的Xcode 6.x和斯威夫特的1.x其中do-try-catch語法不可用(僅Xcode中7和夫特2)

此代碼具有等效的行爲:

func json_parseData(data: NSData) -> NSDictionary? { 
    var error: NSError? 

    // passing the error as inout parameter 
    // so it can be mutated inside the function (like a pointer reference) 
    let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainerserror: &error) 

    if error == nil { 
     print("[JSON] OK!") 
     return (json as? NSDictionary) 
    } 
    print("[ERROR] An error has happened with parsing of json data") 
    return nil 
} 

注:如Xcode的7測試6也可以使用try?如果發生錯誤,它返回nil

+0

可以是你說的沒錯! – Ast