是否可以满足Swift协议并添加默认参数? [英] Is it possible to satisfy Swift protocol and add defaulted arguments?

查看:295
本文介绍了是否可以满足Swift协议并添加默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有这样的协议:

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) {}
}

这很高兴,因为通过添加默认参数可以满足协议的结果签名.有什么办法可以使它与Swift 2一起使用?

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?

这是一个简化的示例.出于争论的原因,假设协议是固定的.解决方案只能更新Messager类.我的目标是能够像这样呼叫sendMessage():

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) {}
}

这种方法的问题在于,我的默认值然后在两个地方指定,而我失去了Swift的默认参数的主要优点.

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.

推荐答案

Swift 3 中,您可以使用扩展程序来解决该问题,但是这有点难看.希望在下一个快速版本中提供更好的解决方案.

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)

这篇关于是否可以满足Swift协议并添加默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆