【问题标题】:May I implement one function of protocol in subclass?我可以在子类中实现协议的一项功能吗?
【发布时间】:2015-12-31 03:55:41
【问题描述】:

我刚刚修改了它。另一个问题是,如果我想从 BaseParticipant 继承一个子类,我可以在子类中重新实现func performEvent 吗? 例如:

class CyclingParticipant: BaseParticipant, Participant
{
init(name: String)
{
    super.init(name: name, preferredEvent: Event.CYCLING)

}

func performEvent(event: Event, distance: Distance) throws
{

}

}

但编译器说“CyclingParticipant 与协议 Participant 的冗余一致性。

class BaseParticipant: Participant
{
 var name: String
 var preferredEvent: Event
 var raceTime: Int
 var couldNotFinish: Bool
 //var performedEvent: Event
// in swift, the class accepts protocol must impletment all funcs inside protocol

init(name: String, preferredEvent: Event)
{
    self.name = name
    self.preferredEvent = preferredEvent
    self.raceTime = 0
    self.couldNotFinish = false
}

func getName() -> String
{
    return self.name
}

func getPreferredEvent() -> Event
{
    return self.preferredEvent
}

func isDisqualified() -> Bool
{
    return self.couldNotFinish
}

func addTime(addtionalRaceTime:Int) -> Void
{
    self.raceTime += addtionalRaceTime
}

func setCouldNotFinish() -> Void
{
    self.couldNotFinish = true
}
func performEvent(event: Event, distance: Distance) throws -> Int
{
    return 1
}
func getTime() throws
{

}

}

协议参与者代码:

protocol Participant
{
func getName() -> String
func getPreferredEvent() -> Event
func isDisqualified() -> Bool
func performEvent(event: Event,distance: Distance) throws ->Int
func addTime(addtionalRaceTime: Int)
func setCouldNotFinish()
func getTime() throws

}

【问题讨论】:

  • getTime() 在哪里实现? performEvent() 既不返回 Int,也不抛出异常。
  • getTime()addTime() 不同。

标签: objective-c swift class protocols


【解决方案1】:

您缺少协议中列出的getTime() 函数的实现。此外,您应该在 Piazza 上发布此类问题。 :P

[更新以回答改写的问题]

BaseParticipant 类已经采用了Participant 协议,所以CyclingParticipant 子类不应该声明它也采用它,这会导致冗余一致性错误。因为BaseParticipant 已经是Participant,所以BaseParticipant 的任何子类也将是Participant

变化:

class CyclingParticipant: BaseParticipant, Participant

到:

class CyclingParticipant: BaseParticipant

【讨论】:

  • 我想既然你是校外的全职员工,也许你下课后会很忙……
  • 我们都使用堆栈溢出。 :D
  • 我无法在子类中重新实现属于协议的函数,就像我的更新一样。我们可以在 swift 中重新实现它吗?
  • 您必须在基类中实现所有协议方法。你不能像在 Java 中那样在 Swift 中创建一个类 abstract。您可以覆盖子类中的函数,但不能声明子类也采用协议,这是它给您的错误。
【解决方案2】:

默认情况下,Swift 协议中声明的所有方法都是必需的。

getTime() 未实现

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    相关资源
    最近更新 更多