Fattie
Fattie

Reputation: 12621

Weird Swift 3 issue with latest Amazon AWS Mobile sample code

Following along the current sample code for aws.amazon.com/mobile/ there are a number of code items they have not updated really well to Swift 3 (which is pretty bizarre considering their resources).

When you come to AWSMobileClient.swift there's a line of code like this:

 if (!isInitialized) {
 AWSIdentityManager.defaultIdentityManager().resumeSession(completionHandler:
   {(result: AnyObject?, error: NSError?) -> Void in
    print("Result: \(result) \n Error:\(error)")
    } as! (Any?, Error?) -> Void)
 isInitialized = true
 }

which just crashes on any run.

Fortunately I was able to fix it by changing the arguments like so

  AWSIdentityManager.defaultIdentityManager().resumeSession(completionHandler:
        {(result: Any?, error: Error?) -> Void in
            print("Result: \(result) \n Error:\(error)")
        } as! (Any?, Error?) -> Void)

The problem is this, I get the warning

enter image description here

indeed it seems pointless trying to cast it to the same type.

BUT if you simply delete the cast

AWSIdentityManager.defaultIdentityManager().resumeSession(completionHandler:
       {(result: AnyObject?, error: NSError?) -> Void in
        print("Result: \(result) \n Error:\(error)")
        }
     isInitialized = true

that just doesn't work at all, you get all sorts of weird syntax errors

enter image description here

1) Why is there a cast there anyway?

2) How can I get rid of the cast, or write it properly so there's no identical cast and hence no warning?

3) I guess a solution is just to remove the force (so, as rather than as!) but I really don't understand why you have to cast the block there.


Note - at that same line of code, Amazon include a comment "If you get an EXC_BAD_ACCESS here in iOS Simulator, then do Simulator -> Reset Content and Settings..., This will clear bad auth tokens stored by other apps with the same bundle ID." The issue I'm asking about here is totally unrelated to that.

Upvotes: 3

Views: 354

Answers (1)

vadian
vadian

Reputation: 285079

In the last example which is presumably the proper syntax the closing parenthesis is missing.

You replaced

} as (Any?, Error?) -> Void)

with

} rather than expected })

I deleted everything which is not mandatory to make it clearer:

WSIdentityManager.defaultIdentityManager().resumeSession(completionHandler: { (result, error) in
    print("Result: \(result) \n Error:\(error)")
})
isInitialized = true

or still shorter with trailing closure syntax:

WSIdentityManager.defaultIdentityManager().resumeSession() { (result, error) in
    print("Result: \(result) \n Error:\(error)")
}
isInitialized = true

The type annotations (in completion blocks) are not needed. They could do more harm than good.

PS: Isn't isInitialized supposed to be in the completion block?

Upvotes: 4

Related Questions