If you have protocol like so:
protocol Messaging { func sendMessage(message: String) }
Is there any way to satisfy it in a class like so:
class Messager: Messaging { func sendMessage(message: String, count: Int = 1) {} }
This would be nice to have, as the resulting signature of the protocol is satisfied by adding the defaulted parameter. Is there any way to get this to work with Swift 2?
This is a simplified example. Let's say, for the sake of argument, that the protocol is fixed. A solution can only update the Messager class. My goal is to be able to call sendMessage()
like so:
let m: Messaging = Messager() m.sendMessage("")
The only way I found to accomplish this (and satisfy the compiler) is with overloading like so:
class Messager: Messaging { func sendMessage(message: String) { self.sendMessage(message, count: 1) } func sendMessage(message: String, count: Int = 1) {} }
The problem with this approach is that my defaults are then specified in two places and I lose the main advantage of Swift's default parameters.
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.
In C++ programming, we can provide default values for function parameters. If a function with default arguments is called without passing arguments, then the default parameters are used. However, if arguments are passed while calling the function, the default arguments are ignored.
Protocol Default Implementation “You can use protocol extensions to provide a default implementation to any method or computed property requirement of that protocol.” In fact, not only can you provide a default implementation to methods or computed properties defined in the protocol, you can also add new ones.
in Swift 3 you could use extensions to solve that, however its a bit ugly. Hope for a better solution in next swift versions.
import UIKit protocol TestProtocol { func testFunction(a:Int, b:Int?) -> String } extension TestProtocol { func testFunction(a:Int, b:Int? = nil) -> String { return testFunction(a:a, b:b) } } class TestClass: TestProtocol { func testFunction(a:Int, b:Int?) -> String { return "a:\(a), b:\(b)" } } func testit(testProtocol: TestProtocol) { print(testProtocol.testFunction(a:10)) // will print a:10, b:nil print(testProtocol.testFunction(a:10, b:20)) // will print a:10, b:Optional(20) } let t = TestClass() testit(testProtocol: t)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With