Reputation: 29896
I have a number of objects, and each need to be locked until purchased.
Each of these objects (NSManaged) have a productName String
and isPurchased Bool
.
I wrote a function isLocked()
which uses there properties as well an external check in a singleton.
How can this be combined into a protocol so that the protocol contains the isLocked function implementation and the objects can just adhere to the protocol and then call isLocked when needed?
Upvotes: 0
Views: 975
Reputation: 1585
If im not mistaken this can be achieved with Default implementations in swift.
protocol Locakable {
var productName: String { get }
var isPurchased: Bool { get }
func lock()
func unlock()
}
extension Locakable {
func isLocked() {
if isPurchased {
//do something
//lock it
unlock()
} else {
lock()
}
}
}
For more info on what mixin or default implementation is then chek out this wiki page https://en.wikipedia.org/wiki/Mixin
However, note that isLocked()
is dispatched statically. Comment if something is unclear.
You can also abstract the idea of locking and unlocking and write a default implementation on the protocol extension if possible. Or provide a customisation point like so.
class Item: Locakable {
var productName = "ItemName"
var isPurchased = false
init () {
isLocked()
}
func lock() {
}
func unlock() {
}
}
Upvotes: 2