本文介绍了协议中的Swift协议属性-候选类型不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个协议(ProtocolA),其中包含与第二个协议(ProtocolB)一致的单个属性.

I have a protocol (ProtocolA) containing a single property conforming to a second protocol (ProtocolB).

public protocol ProtocolA {        
    var prop: ProtocolB? { get }
}

public protocol ProtocolB {        
}

我正在尝试声明两个将实现这些类的类:

I'm trying to declare two classes that will implement those:

private class ClassA : ProtocolA {    
    var prop: ClassB?
}

private class ClassB : ProtocolB {
}

但是我得到一个错误:

协议要求类型为"ProtocolB?"的属性"prop"

Protocol requires property 'prop' with type 'ProtocolB?'

候选人具有不匹配的类型"ClassB?"

Candidate has non-matching type 'ClassB?'

哪些令人讨厌,因为ClassB符合ProtocolB.

Which is annoying as ClassB conforms to ProtocolB.

在旧版本中,我可能只是将该属性声明为:

in the good-old i'd probably just declare the property as:

@property (nonatomic) ClassB <ProtocolB> *prop;

但是看来我可以快速解决此问题的唯一方法是添加一个像这样的ivar:

but the only way it seems I can get around this in swift is by adding an ivar like:

private class ClassA : ProtocolA {        
    var _prop: ClassB?
    var prop: ProtocolB? { return _prop }
}

有没有办法解决这个问题?

Is there no way around this?

推荐答案

您需要声明符合其他协议类型的typealias.这样做的方式是prop必须完全是ProtocolB类型,但是您实际上并不需要它,而是想要一个符合它的类型.

You need to declare a typealias of the type that conforms to the other protocol. The way you did it is that prop has to be exactly of type ProtocolB, but you don't actually want that, you want a type that conforms to it instead.

protocol ProtocolA {
    typealias Prop : ProtocolB
    var prop: Prop? { get }
}

protocol ProtocolB {}


class ClassA : ProtocolA {
    var prop: ClassB?
}

class ClassB : ProtocolB {}

这篇关于协议中的Swift协议属性-候选类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:01