I ask a question today because I’m little bit lost today. It’s about Swift and protocol and more about Protocol Oriented Programming (POP).
I read articles about it, even a book but I’m still confused. Everybody seems to say that Protocol is a great tool and so on but I don’t really understand its power.
I’ve a question because I’m coding a class Volume which is the representation of a volume as an object. Let’s say
struct Volume {
var value: Float = 1
var isLogScale: Bool = false
var maxLogVolume: Float = 6.0 // value in dB
var maxLinearVolume: Float = 1.0
let dynamicRange: Float = 50.0
func convertLinearToLog() -> Float {
// Do some maths
}
func otherFunction() {
print("Hello, I'm the most useless function in the world.")
}
}
This is a typical class nothing special.
But… Should I better us a protocol like this:
protocol VolumeProtocol {
var value: Float {get set}
var isLogScale: Bool {get set}
var maxLogVolume: Float {get set}
var maxLinearVolume: Float {get set}
let dynamicRange: Float {get}
func convertLinearToLog() -> Float
func otherFunction()
}
And then re implement everything like
struct MyVolumeClass: VolumeProtocol {
// Same thing as before
}
I don’t really manage to answer to this question, so if you could help me when to use protocol and when not I would appreciate.
VolumeProtocol, since I don't suppose you would have several different classes conforming to this protocol.volume,audioFormatand classessingleAudioPlayermultipleAudioPlayerthat conform to the previous protocols. It's still not natural for me to do that because writing "protocol" with just declaration still seems useless for me (I only used protocol for delegate pattern) but it helps for the maintenance of the code