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
  • 5,147
  • 8
  • 39
  • 60
  • 1
    What does `myProtocol` look like? – Sweeper Nov 19 '21 at 10:10
  • 1
    Well, both `method1` and `method2` are static requirements. – Sweeper Nov 19 '21 at 10:17
  • @Sweeper Are there other kinds of "static requirements"? I don't understand why there is a problem here and how to overcome it. – Artium Nov 19 '21 at 10:18
  • 1
    See [here](https://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself) for an explanation. – Sweeper Nov 19 '21 at 10:20
  • I still don't see the definition for the MyProtocol Class. How does EVDInputModel factor into this? I don't see it being used anywhere. – Yogurt Nov 19 '21 at 23:05
  • 1
    @Biclops Updated the question. Sorry for the confusion, copy pasted real code and forgot to translate it into the example. – Artium Nov 20 '21 at 00:36

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
}
Yogurt
  • 2,913
  • 2
  • 32
  • 63