1

When trying to use code from ObjC in Swift, I encountered the following Swift error:

'myClass & myProtocol' cannot be used as a type conforming to protocol 'myProtocol' because 'myProtocol' has static requirements

The code looks roughly like this:

@interface FooGenericContainer <T : MyClass < MyProtocol > *> : MyClass
func asFoo() -> FooGenericContainer<MyClass & MyProtocol> { /// <-- error here
  ....
}

@protocol MyProtocol <NSObject, NSCopying, NSMutableCopying, AnotherProtocol>
@end

...

@protocol AnotherProtocol <NSObject, NSCopying, NSMutableCopying>

+ (NSDictionary *)method1;

@optional

+ (NSDictionary *)method2;

@end

What are "static requirements" of a protocol, are these the class methods it have?

How can I overcome this error?

Can I return FooGenericContainer without specifying the generic type?

Artium
  • 4,867
  • 8
  • 37
  • 59

1 Answers1

1

I got past the error by adding <MyProtocol> To the MyClass definition

This is the code I used

// copied from a header that's included in the bridging header in OBJC

@protocol AnotherProtocol <NSObject, NSCopying, NSMutableCopying>
+ (NSDictionary *)method1;
@optional
+ (NSDictionary *)method2;
@end

@protocol MyProtocol <NSObject, NSCopying, NSMutableCopying, AnotherProtocol>
@end

//  Note: if I didn't include '<MyProtocol>' it would give me the static requirement error
@interface MyClass <MyProtocol>
@end

@interface FooGenericContainer <T: MyClass<MyProtocol> *> : MyClass
@end

Then in swift


// I made this optional just to get it to compile
func asFoo() -> FooGenericContainer<MyClass & MyProtocol>? {
    return nil
}
Biclops
  • 2,747
  • 2
  • 27
  • 59