Overriding AnyObject to a more specific type

Hi there,

I’ve hit a bit of a wall on trying to figure out how best to solve the following situation:

I’ve got a protocol that requires the following method for all objects that implement it:

protocol OperationDataProvider { func provideData() -> OperationResultType? }

I’m trying to declare several “types” that all behave in a similar fashion. I’ve created the following protocol in hopes that each type that implements it can override the “AnyObject” defined within the protocol:

protocol OperationResultType { var result: AnyObject? { get } var error: NSError? { get } }

I’m then trying to create other types that can specify the type of “result”:

TestOperationResult<T>: OperationResultType { var result: T? var error: NSError? }

I’m using a generic to try and infer the type based on the type when the TestOperationResult is created.

Unfortunately, I’m running into an issue as it doesn’t appear that I can override result to be anything other than AnyObject

Is it possible to achieve what I’m attempting to do?

Any help and/or direction would be very much appreciated.

Thank you!
Frank

I would always use OperationResultType there instead of AnyObject. Essentially it is still a generic but one guaranteed to conform to the protocol, which is what you want.

If each conformer to OperationResultType should be able to specify its type of result, then in principle you would need an associated type.

protocol OperationResultType {
  associatedtype Result : AnyObject
  var result : Result? { get }
  var error: NSError? { get } 
}

However, it’s not quite that simple, because OperationDataProvider.provideData() can’t now return an OperationResultType any more than it could return an Equatable or an Optional - it has ‘Self’ requirements - and you need to know what the associated type is to make use of it. (e.g. instead of provideData you might need a provideIntData to return an OperationResultType whose result was of type Int). You can make generic types, but you can’t use them to hide what the type is.