Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift-检查是否传递了函数参数_Swift_Default Parameters - Fatal编程技术网

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

Swift-检查是否传递了函数参数,swift,default-parameters,Swift,Default Parameters,假设我有以下功能: func update(a a: String? = nil, b: String? = nil) { if a.notDefaultValue /* or something like that */ { // ... } if b.notDefaultValue { // ... } } 我可以这样称呼它(希望在评论中也这样称呼): 我怎样才能做到这一点 编辑: 我能想到的唯一方法是使用方法重载,但当您有

假设我有以下功能:

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

    if b.notDefaultValue {
        // ...
    }
}
我可以这样称呼它(希望在评论中也这样称呼):

我怎样才能做到这一点

编辑:


我能想到的唯一方法是使用方法重载,但当您有许多参数时,这是不可行的(甚至不必那么多,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.
    }
}

也试着写这样的东西:

func hello() {
    print("hello")
}

func hello(name: String) {
    print("hello \(name)")
}

func hello(name: String, last: String) {
    print("hello \(name) \(last)")
}

hello()
hello("arsen")
hello("arsen", last: "gasparyan")

这是一种更实用的方法

您可以简单地检查指定的参数是否具有默认值,在您的例子中是nil。但是这不会区分
update()
update(a:nil)
2^4是16,而不是17:)Rodrigo,前4个update()示例的调用流没有区别。更新函数体中a和b参数的本地值将为零,无论它们是从调用方显式复制的还是由默认参数初始值设定项复制的。我知道,这是我的问题,我希望这4个参数不同。这不会区分
update()
update(a:nil)
我想你不能,如果你不传递任何参数,a和b也将为零,传递布尔值会容易得多,而这正是我想要的。我希望调用与我的问题中的调用相同。@RodrigoRuiz诀窍是不定义=nil,否则,只要占位符(默认参数)是私有的(即调用方不知道),就不能在没有任何参数的情况下调用它,当参数等于占位符时,您应该非常确信调用方没有提供任何参数。我可以这样做(但一定要使用GUID),尽管这有点老套,对于其他参数line
Int
,效果不太好。就像我问题的最后一样,这是不可行的,如果我有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.
    }
}
func hello() {
    print("hello")
}

func hello(name: String) {
    print("hello \(name)")
}

func hello(name: String, last: String) {
    print("hello \(name) \(last)")
}

hello()
hello("arsen")
hello("arsen", last: "gasparyan")