Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

swift2 - Is it possible to satisfy Swift protocol and add defaulted arguments?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...