Adam Vukich
Adam Vukich

Reputation: 303

Use Swift to interact with an Objective C method that expects a block as an argument

I am trying to write some Swift code that calls an existing Objective C function. The Objective C function looks like:

+(void) getCurrentUserprofileWithCompletion:(RequestCallback)completion {...}

where RequestCallback is defined in a .h file as:

typedef void (^RequestCallback) (ResponseInfo *responseInfo);

I have tried a number of different things, but nothing seems to work. The code that looks the most logical to me is:

let callback: (responseInfo: ResponseInfo) -> Void = {(responseInfo: ResponseInfo) -> Void in
    if let organization: Organizations = Organizations.organizationWithId(orgId) {
        completionBlock(false, nil)
    } else {
        self.switchOrganization(user, organization: organization, completionBlock: completionBlock)
    }
}
Users.getCurrentUserprofileWithCompletion(callback)

but this is getting the error

cannot convert value of type '(responseInfo: ResponseInfo) -> Void' to expected argument type 'RequestCallback!'

Does anyone have any idea what I am doing wrong here? I have scoured the internet looking for help including the various Apple documentation, but either I am blind or misreading because nothing seems to be working.

Thanks in advance!

Upvotes: 0

Views: 117

Answers (1)

Aleš Kocur
Aleš Kocur

Reputation: 1898

Just remove the type specification for responseInfo a use the type RequestCallback

let callback: RequestCallback = { responseInfo -> Void in
    if let organization: Organizations = Organizations.organizationWithId(orgId) {
        completionBlock(false, nil)
    } else {
        self.switchOrganization(user, organization: organization, completionBlock: completionBlock)
    }
}

Users.getCurrentUserprofileWithCompletion(callback)

Upvotes: 1

Related Questions