【问题标题】:What are the static requirements of Swift protocol?Swift 协议的静态要求是什么?
【发布时间】:2021-12-30 02:55:48
【问题描述】:

在 Swift 中尝试使用 ObjC 中的代码时,我遇到了以下 Swift 错误:

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

代码大致如下:

@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

什么是协议的“静态要求”,这些是它具有的类方法吗?

我该如何克服这个错误?

我可以返回FooGenericContainer 而不指定泛型类型吗?

【问题讨论】:

  • myProtocol 长什么样子?
  • @Sweeper 更新问题。
  • 嗯,method1method2 都是静态要求。
  • 请参阅here 以获得解释。
  • @Biclops 更新了问题。很抱歉造成混乱,复制粘贴的真实代码并忘记将其翻译成示例。

标签: swift objective-c


【解决方案1】:

我通过在 MyClass 定义中添加 &lt;MyProtocol&gt; 来解决错误

这是我使用的代码

// 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

然后迅速


// I made this optional just to get it to compile
func asFoo() -> FooGenericContainer<MyClass & MyProtocol>? {
    return nil
}

【讨论】:

  • 如果这不起作用,MyClass 的类声明是什么样的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
  • 2015-12-26
  • 1970-01-01
  • 2017-08-06
  • 2016-05-30
相关资源
最近更新 更多