1

I am using an NSOperation that conforms to SomeProtocol that has a results property

let op : NSOperation, SomeProtocol = ...

op.completionBlock = {
    print(op.results)
}

I get the following error:

Value of type 'NSOperation' has no member 'results'

I know that I can subclass NSOperation to get the intended behaviour, but can I achieve what I want using protocols?

GangstaGraham
  • 8,865
  • 12
  • 42
  • 60

1 Answers1

3

That code shouldn't even get that far... unlike Objective-C, Swift does not allow specifying a variable as a combination of both a concrete type AND a protocol. You can only declare a variable to be of a specific type, a specific protocol, or a composition of protocols, e.g.

let op : protocol<SomeProtocol, AnotherProtocol> = ...

But there is currently no way to declare a variable as being of the specific type NSOperation AND conforming to the protocol SomeProtocol

Daniel Hall
  • 13,457
  • 4
  • 41
  • 37
  • Interesting, the compiler accepted the variable's definition. So there's no way to define a variable with a specific type that also conforms to a specific protocol? Also, protocols are types, aren't they? https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID275 – GangstaGraham May 30 '16 at 23:37
  • Thanks for the help! Will accept this as the answer whenever I can – GangstaGraham May 30 '16 at 23:39
  • @GangstaGraham You can use generics to help: http://stackoverflow.com/questions/25767156/swift-property-conforming-to-a-specific-class-and-in-the-same-time-to-multiple?rq=1 – Daniel Hall May 30 '16 at 23:42
  • I actually tried something similar to generics before I posted the question, I tried to do it like `let op = ` but that didn't work. Thanks for posting the link. I ended up using subclassing because I needed to use static stored properties which aren't supported in generic types yet – GangstaGraham May 30 '16 at 23:57
  • @GangstaGraham Yeah, Swift generics are still not complete and you can't have generics constraints in a variable declaration. So that solution won't work everywhere, but it might be a better alternative than subclassing for you. You could make a `class NSOperationWrapper : SomeProtocol` Inside that class, you would hold a reference to the real NSOperation and forward methods / property access to the underlying NSOperation. Then you could say `let op = NSOperationWrapper(operation: theOperation)` and use that as your type + protocol – Daniel Hall May 31 '16 at 00:03