Frederick C. Lee
Frederick C. Lee

Reputation: 9513

Translating ObjC return type (id<protocol>) to its Swift 3.0 equivalent

I'm getting a bit confused on how to translate an Objective-C method signature into its Swift 3.0 equivalent.

The following is the original Objective-C method using the return type of 'id' with its UIViewControllerAnimatedTransitioning protocol:

Objective-C

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return self;
}

I wish to translate the Objective-C version into its corresponding Swift 3.0 equivalent:

Swift 3.0

func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return self
    }

Is the Swift 3.0 version correct?

...or should I use the AnyObject? return type:

enter image description here ...from which I get the warning; and what about handling the (id) signature?

More specifically, should 'id' be translated to protocol? type?

Here's the compiler's "solution": enter image description here

What's the correct format?


This is what the compiler returned: enter image description here

Upvotes: 1

Views: 467

Answers (2)

Frederick C. Lee
Frederick C. Lee

Reputation: 9513

Based on ricster's answer, I recheck my code.

I discovered that I didn't adopt the protocol per stated Objective-C source in the host (self) and hence, got the Swift 3.0 compiler complaint:

enter image description here

Upvotes: 0

rickster
rickster

Reputation: 126167

Yes, the protocol name alone is the full type when translating id<SomeProtocol> from ObjC to Swift. (You don't need to translate anything about the thing conforming to the protocol being id. The protocol comes in from ObjC, so the only things that can conform to it are objects — that is, your protocol is implicitly a subtype of AnyObject.)

In your case, optional func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? is also the official translation of that delegate method signature.

Declaring your method as returning AnyObject? instead breaks the delegate method signature, which won't work right because it shares the same ObjC selector with the correct method. (And making the incorrect signature @nonobjc guarantees it won't be called.)

Upvotes: 2

Related Questions