Loc Pham
Loc Pham

Reputation: 617

Value of optional type '()?' not unwrapped

As far as I can tell, the optional failure block in the code below is already unwrapped with the ? but xCode has been complaining about my syntax. If you look closely at the success block, it looks exactly like the failure block but somehow, xCode isn't flagging the success block. I've encountered this problem before and managed to get rid of the problem with a build clean, but not this time. Has anyone encountered similar problems?

public func authorizeLogin(token: String, success: (() -> ())?, failure: (() -> ())?) {
        let path = "me/two-step/push-authentication"
        let requestUrl = self.pathForEndpoint(path, withVersion: ServiceRemoteRESTApiVersion_1_1)

        let parameters  = [
            "action"        : "authorize_login",
            "push_token"    : token
        ]

        api.POST(requestUrl,
            parameters: parameters,
            success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
                success?()
            },
            failure:{ (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
                failure?()
            })
    }

Here's the screenshot with the error message:

value of optional type '()?' not unwrapped; did you mean to use '!' or '?'

enter image description here

Upvotes: 1

Views: 2048

Answers (1)

Aaron Rasmussen
Aaron Rasmussen

Reputation: 13316

Something looks really fishy in your code...both your failure closure and your success closure seem to be trying to call themselves. For example:

success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
            success?() // <- This appears to be trying to call
                       //    the parameter itself
        }

That will never work. It's like writing,

let add: () -> () = { add() }

which gives the error error: variable used within its own initial value

I think that the error message you are getting is misleading, and what you need to do is write closures for the success and failure parameters that don't call themselves.

Upvotes: 1

Related Questions