解析和 Swift 1.2 问题 [英] Parse and Swift 1.2 issue
本文介绍了解析和 Swift 1.2 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这段代码在 Swift 1.1 中运行良好......只是想弄清楚 1.2 中发生了什么变化以使其不兼容:
This code worked fine in Swift 1.1 ... just trying to figure out what's changed in 1.2 to make it incompatible:
@IBAction func load_click(sender: AnyObject) {
var query = PFQuery(className: "myClass")
query.getObjectInBackgroundWithId("MPSVivtvJR", block: { (object:PFObject!, error: NSError) -> Void in
let theName = object["name"] as String
let theAge = object["age"] as Int?
println(theName)
println(theAge)
})
}
它给了我错误:无法使用类型为 '(String, block: (PFObject!, NSError) -> Void) 的参数列表调用 'GetObjectInBackgroundWithId'
有什么想法吗?谢谢!
推荐答案
现在在 Swift 1.2 中,您应该更加小心地解开可选项.所以在你有 PFObject
和 NSError
的闭包中,要么删除感叹号,要么添加一个问号以使其可选.
Now with Swift 1.2 you are supposed to be more careful with unwrapping optionals. So inside the closure where you have PFObject
and NSError
, either remove the exclamation marks or add a question mark to make it optional.
然后,更安全地打开您的对象.尝试如下:
Then, unwrap your object more safely. Try as follows:
// You can create this in a separate file where you save your models
struct myUser {
let name: String?
let age: Int?
}
// Now this in the view controller
@IBAction func load_click(sender: AnyObject) {
var query = PFQuery(className: "myClass")
query.getObjectInBackgroundWithId("MPSVivtvJR", block: {
(object:PFObject!, error: NSError?) -> Void in
if let thisName = object["name"] as? String{
if let thisAge = object["age"] as? Int{
let user = myUser(name: thisName, age: thisAge)
println(user)
}
}
})
}
这篇关于解析和 Swift 1.2 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文