这是我得到的:
do {
try let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(paramsDict, options: NSJSONWritingOptions.PrettyPrinted)
jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
} catch {
print("CAUGHT SOMETHING session token")
}
我收到错误try must be placed on the initial value expression
。我像这样尝试'改述':
do {
let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(paramsDict, options: NSJSONWritingOptions.PrettyPrinted)
try jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
} catch {
print("CAUGHT SOMETHING session token")
}
但这会导致错误Call can throw but is not marked with 'try'
。我应该如何构建这个try-catch以及这些错误代码的含义是什么?
你必须改变你放置try
的位置。
do {
if let jsonData: NSData = try NSJSONSerialization.dataWithJSONObject(paramsDict, options: NSJSONWritingOptions.PrettyPrinted) {
//is jsonString a variable you have previously declared?
//if not, put "if let" before it, because you are creating it IF:
//your "try" - attempt to get data from json succeeds
jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
}
} catch {
print("CAUGHT SOMETHING session token")
}