2

In Objective-C, you can specify both a class name and a set of protocols in a return value. For example, a UIViewController that is a UIScrollViewDelegate:

- (UIViewController<UIScrollViewDelegate> *) viewDelegate;

I can't find a way to express this in Swift. Something like this fails, since UIViewController is not a protocol:

func viewDelegate() -> protocol<UIViewController, UIScrollViewDelegate>;
kvance
  • 1,479
  • 18
  • 22
  • Just wondering why you need a protocol declaration on the return type? – Woodstock Feb 13 '15 at 20:28
  • @Woodstock the return value needs to implement methods from both the class and the protocol. It would be nice for the type checker to enforce that instead of checking at runtime. – kvance Feb 13 '15 at 20:33

1 Answers1

1

You can make a generic function with a constraint. Does this satisfy your use case?

  func viewDelegate<T: UIViewController, UIScrollLViewDelegate>() -> T {

    var t = T()

    return t;

  }
fred02138
  • 3,323
  • 1
  • 14
  • 17
  • That looks good! But I should have mentioned this project is still mostly Objective-C, and it looks like generic functions aren't backwards compatible.I get the compiler error `Method cannot be marked @objc because its result type cannot be represented in Objective-C` since it's `@objc`. – kvance Feb 13 '15 at 20:36
  • 1
    Marking as the solution, since I don't think there's a way to do this that's ObjC compatible. – kvance Feb 14 '15 at 20:24