gpt4 book ai didi

swift - 协议(protocol)子类实现

转载 作者:行者123 更新时间:2023-11-28 05:29:52 25 4
gpt4 key购买 nike

我有以下代码,我试图在其中强制抽象(抽象类/一致性):

播放器协议(protocol):

protocol PlayerProtocol {
func play();
func stop();
func pause();

func getVolume() -> UInt32;
func setVolume(level: UInt32);

func isPaused() -> Bool;
func isStopped() -> Bool;

func onSessionResume();
func onSessionInterupt();
}

基本播放器:

class BasicPlayer : PlayerProtocol {
//some variables here..

init() {
//init some variables here..
}

func play() {
fatalError("play() - pure virtual function called.");
}

func stop() {
fatalError("stop() - pure virtual function called.");
}

func pause() {
fatalError("stop() - pure virtual function called.");
}

func getVolume() -> UInt32 {
fatalError("getVolume() - pure virtual function called.");
}

func setVolume(level: UInt32) {
fatalError("setVolume() - pure virtual function called.");
}

func isPaused() -> Bool {
fatalError("isPaused() - pure virtual function called.");
}

func isStopped() -> Bool {
fatalError("isStopped() - pure virtual function called.");
}

func onSessionInterupt() {
fatalError("onSessionInterupt() - pure virtual function called.");
}

func onSessionResume() {
fatalError("onSessionResume() - pure virtual function called.");
}
}

音频播放器:

class AudioPlayer : BasicPlayer, PlayerProtocol {
private var device: COpaquePointer = nil;
private var context: COpaquePointer = nil;
private var source: ALuint = 0;
private var buffer: ALuint = 0;
private var interrupted: Bool = false;
private var volume: Float = 50;


override init() {
super.init();
//..
}

deinit {
//..
}

override func play() {
//..
}

override func stop() {
//..
}

override func pause() {
//..
}

override func setVolume(volume: UInt32) {
//..
}

override func getVolume() -> UInt32 {
//..
}

func isPlaying() -> Bool {
//..
}

override func isPaused() -> Bool {
//..
}

override func isStopped() -> Bool {
//..
}

func isAudioPlaying() -> Bool {
return AVAudioSession.sharedInstance().otherAudioPlaying;
}

override func onSessionInterupt() {
self.pause();
}

override func onSessionResume() {
self.play();
}

func setData(buffer: ALuint, source: ALuint) {
self.buffer = buffer;
self.source = source;
}
}

但是即使我指定AudioPlayer实现了PlayerProtocol,它并没有强制我实现所有的成员函数,比如playstop 等。我可以删除它们并且它不会提示。这可能是因为父类(super class)实现了它,但我无法弄清楚如何在父类(super class)中保留它未实现并允许派生类代替实现。

基本上,BasicPlayer 应该是抽象的,任何继承它的类都必须实现“某些”成员(不是全部)。 OnSessionInterrupt 未在派生类中实现。我需要它来出错。

我该怎么做?如何在派生类而非抽象类中的未实现成员的编译时使其出错?

最佳答案

AudioPlayer 是已经符合 PlayerProtocol 的类的子类。因为您已经在父类(super class)中实现了所有方法,所以这些实现在您的子类中可用,因此您不必重新声明它们。

在我看来,您似乎是通过两种不同的方式在概念上抽象您的接口(interface):通过协议(protocol)和通过抽象父类(super class)。这可能是多余的?一个或另一个应该能够满足您的目的。

关于swift - 协议(protocol)子类实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29201850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com