Swift:条件绑定中的绑定值必须是可选的

时间:2015-07-16 12:28:00

标签: xcode swift types conditional optional

我在这行代码中遇到错误:

if let installation = PFInstallation.currentInstallation() 

完整代码如下。它在Swift的早期版本中工作,但由于某种原因现在出现编译错误。任何想法是什么问题?

class func logInWithFacebook() {
PFFacebookUtils.logInWithPermissions(["public_profile"], block: {
    (user: PFUser?, error: NSError?) -> Void in

    if user == nil {
        NSLog("The user cancelled the Facebook login (user is nil)")
    } else {
        NSLog("The user successfully logged in with Facebook (user is NOT nil)")

        if let installation = PFInstallation.currentInstallation() { // ERROR
            let acl = PFACL(user: PFUser.currentUser()!) // 
            acl.setPublicReadAccess(true) 
            acl.setWriteAccess(true, forRoleWithName: "Admin") 
            installation.ACL = acl
            installation.saveEventually()
        }
        // THEN I GET THE USERNAME AND fbId
        Utils.obtainUserNameAndFbId()
    }
})
}

1 个答案:

答案 0 :(得分:0)

这意味着PFInstallation.currentInstallation()的返回类型必须是可选的,如果它在if let声明的行中被解包。

现在,该调用会返回PFInstallation对象(不是PFInstallation?Optional(PFInstallation))。如果这在“之前”工作,也许你的意思是在swift 1.2之前引入了Objective C互操作性的一些变化。

请参阅https://parse.com/docs/ios/api/Classes/PFInstallation.html#//api/name/currentInstallation

上的文档

要更正您的代码,请移除if let行:

class func logInWithFacebook() {
    PFFacebookUtils.logInWithPermissions(["public_profile"], block: {
        (user: PFUser?, error: NSError?) -> Void in

        if user == nil {
            NSLog("The user cancelled the Facebook login (user is nil)")
        } else {
            NSLog("The user successfully logged in with Facebook (user is NOT nil)")


            let acl = PFACL(user: PFUser.currentUser()!) // 
            acl.setPublicReadAccess(true) 
            acl.setWriteAccess(true, forRoleWithName: "Admin") 
            installation.ACL = acl
            installation.saveEventually()

            // THEN I GET THE USERNAME AND fbId
            Utils.obtainUserNameAndFbId()
        }
    })
}