假设我有以下功能:
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/