Hello so I want to implement something similar in swift
Kotlin example:
class SessionManager(
private val freeManager: FreeManager
) : FreeManager by freeManager
{
}
up here FreeManager is Interface I pass reference through constructor and now I can write in extend part FreeManager by freeManager which doesn't require me to implement all methods from interface how can I achieve something similar in swift with protocols?
Can I do something like this:
class SessionManager : FreeManager {
init(freeManager: FreeManager) {
// assign freeManager to extended protocol instead of implementing
//all needed methods from protocol
}
}
You can achieve what you're looking for using a protocol
and a protocol extension
.
1. Create a protocol
name FreeManager
with 2 methods,
protocol FreeManager {
func method1()
func method2()
}
For now, both method1()
and method2()
are mandatory to implement by the conforming type
.
2.
Create a protocol extension
and implement the method of protocol
that you want to make optional
, ie
extension FreeManager {
func method2() {
print("This is method2()")
}
}
In the above code, I've implemented method2()
in protocol extension
. So, now implementing this method is optional
for the conforming type
. method1()
is still mandatory to implement.
3. Conform class SessionManager
to FreeManager
class SessionManager: FreeManager {
func method1() {
print("This is method1()")
}
}
In the above code, I've implemented only method1()
.
In Swift you can extend the protocol itself:
protocol Foo {
func bar()
}
extension Foo {
func bar() {
print("bar")
}
}
class Bar: Foo {
}
let bar = Bar()
bar.bar()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.