I just found that NSURL
will not automatically show at URL
when it is used in Objective-C with Generics.
On the Swift side I have to use this code to cast. Below is the Objective-C code. Shouldn't NSURL
be implicitly cast to URL
like it is being done on the call to connect
but not with the return type for task
? Should this be reported as a bug?
let client = Client()
let task = client.getEndpointURL()
if let endpointURL = task.result as URL? {
client.connect(withEndpointURL: endpointURL)
}
Headers
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Task<__covariant ResultType> : NSObject
@property (nullable, nonatomic, strong, readonly) ResultType result;
@property (nullable, nonatomic, strong, readonly) NSError *error;
- (instancetype)init;
- (instancetype)initWithResult:(nullable id)result;
- (instancetype)initWithError:(NSError *)error;
+ (instancetype)taskWithResult:(nullable ResultType)result;
+ (instancetype)taskWithError:(NSError *)error;
@end
@interface Client : NSObject
- (Task<NSURL *> *)getEndpointURL;
- (BOOL)connectWithEndpointURL:(NSURL *)endpointURL;
@end
NS_ASSUME_NONNULL_END
Implementations
#import "Task.h"
@interface Task ()
@property (nullable, nonatomic, strong, readwrite) id result;
@property (nullable, nonatomic, strong, readwrite) NSError *error;
@end
@implementation Task
- (instancetype)init {
self = [super init];
if (!self) return self;
return self;
}
- (instancetype)initWithResult:(nullable id)result {
self = [super init];
if (!self) return self;
self.result = result;
return self;
}
- (instancetype)initWithError:(NSError *)error {
self = [super init];
if (!self) return self;
self.error = error;
return self;
}
+ (instancetype)taskWithResult:(nullable id)result {
return [[self alloc] initWithResult:result];
}
+ (instancetype)taskWithError:(NSError *)error {
return [[self alloc] initWithError:error];
}
@end
@implementation Client
- (Task<NSURL *> *)getEndpointURL {
NSURL *result = [[NSURL alloc] initWithString:@"https://api.acme.com/"];
Task<NSURL *> *task = [Task taskWithResult:result];
return task;
}
- (BOOL)connectWithEndpointURL:(NSURL *)endpointURL {
return NO;
}
@end