Swift - 检查函数参数是否已传递

标签 swift default-parameters

假设我有以下功能:

func update(a a: String? = nil, b: String? = nil) {
    if a.notDefaultValue /* or something like that */ {
        // ...
    }

    if b.notDefaultValue {
        // ...
    }
}

我可以用这些方式调用它(期望像评论中那样):

update()               // Should do nothing
update(a: nil)         // Should only go into first 'if' statement
update(b: nil)         // Should only go into second 'if' statement
update(a: nil, b: nil) // Should go into both 'if' statements
update(a: "A")         // Should only go into first 'if' statement
update(b: "B")         // Should only go into second 'if' statement
update(a: "A", b: "B") // Should go into both 'if' statements

我怎样才能实现这个目标?

编辑:

我能想到的唯一方法是使用方法重载,但是当你有很多参数时这是不可行的(甚至不必那么多,4 个就已经需要 17 个方法了)。

最佳答案

我不确定你为什么要这样做,但你可以这样做:

let argumentPlaceholder = "__some_string_value__"

func update(a a: String? = argumentPlaceholder, b: String? = argumentPlaceholder) {
     if a == argumentPlaceholder {
        // Default argument was passed, treat it as nil.
    }

     if b == argumentPlaceholder {
        // Default argument was passed, treat it as nil.
    }
}

关于Swift - 检查函数参数是否已传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32774710/

相关文章:

ios - 如何用 Observable 包装异步函数

ios - 如何通过数组访问.csv文件目录

python - 在 python 中使用 *args 和默认参数

python - "Least Astonishment"和可变默认参数

ios - 在表格 View 重新加载期间绘制线条的问题

ios - UIButton 未使用分配的文本展开

ios - 如何在不提供任何 Controller 的情况下激活相机?

kotlin - 传递 null 时,有没有办法在非可选参数上使用默认值?

c# - 为方法声明默认参数时出错

function - 在Kotlin中将异常用作默认参数