我想知道什么是最佳实践,当我需要一些函数公开和一些内部使用协议时。
我正在写一个AudioManager在Swift 3包装AVPlayer
作为一个框架。
我想要一些方法是公开的,例如使用AudioManager的ViewController可以访问某些方法,但某些方法不会暴露在框架
- >即访问修饰符internal
而不是public
之外。
我正在用协议驱动设计编写框架,几乎每个部分都应该有一个协议。
因此协议正在与框架内的协议交谈。
例如主类 - AudioManager
- 具有AudioPlayer
,并且应该能够调用其上的一些internal
函数,例如
。 pause(reason:)
但该方法应该是internal
而不是暴露在框架之外。
这里是一个例子。具有内部函数和属性的Swift公共协议
internal enum PauseReason {
case byUser
case routeChange
}
// Compilation error: `Public protocol cannot refine an internal protocol`
public protocol AudioPlayerProtocol: InternalAudioPlayerProtocol {
func pause() // I want
}
internal protocol InternalAudioPlayerProtocol {
func pause(reason: PauseReason) // Should only be accessible within the framework
}
public class AudioPlayer: AudioPlayerProtocol {
public func pause() {
pause(reason: .byUser)
}
// This would probably not compile because it is inside a public class...
internal func pause(reason: PauseReason) { //I want this to be internal
// save reason and to stuff with it later on
}
}
public protocol AudioManagerProtocol {
var audioPlayer: AudioPlayerProtocol { get }
}
public class AudioManager: AudioManagerProtocol {
public let audioPlayer: AudioPlayerProtocol
init() {
audioPlayer = AudioPlayer()
NotificationCenter.default.addObserver(self, selector: #selector(handleRouteChange(_:)), name: NSNotification.Name.AVAudioSessionRouteChange, object: nil)
}
func handleRouteChange(_ notification: Notification) {
guard
let userInfo = notification.userInfo,
let reasonRaw = userInfo[AVAudioSessionRouteChangeReasonKey] as? NSNumber,
let reason = AVAudioSessionRouteChangeReason(rawValue: reasonRaw.uintValue)
else { print("what could not get route change") }
switch reason {
case .oldDeviceUnavailable:
pauseBecauseOfRouteChange()
default:
break
}
}
}
private extension AudioManager {
func pauseBecauseOfRouteChange() {
audioPlayer.pause(reason: .routeChange)
}
}
// Outside of Audio framework
class PlayerViewController: UIViewController {
fileprivate let audioManager: AudioManagerProtocol
@IBAction didPressPauseButton(_ sender: UIButton) {
// I want the `user of the Audio framwwork` (in this case a ViewController)
// to only be able to `see` `pause()` and not `pause(reason:)`
audioManager.audioPlayer.pause()
}
}
我知道我可以得到它通过改变方法pauseBecauseOfRouteChange
工作看起来像这样:
func pauseBecauseOfRouteChange() {
guard let internalPlayer = audioPlayer as? InternalAudioPlayerProtocol else { return }
internalPlayer.pause(reason: .routeChange)
}
但我想知道如果有一个更好的解决方案?
类似于标记AudioPlayerProtocol
细化了InternalAudioPlayerProtocol
...
或者你们是如何做到这一点的?
如果该框架不公开用于内部使用的方法和变量,则该框架更美观!
谢谢!