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

时间:2015-09-25 04:14:40

标签: 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个方法)。

3 个答案:

答案 0 :(得分:2)

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

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.
    }
}

答案 1 :(得分:1)

func update(a a: String?, b: String?) {
    if let a = a, b = b  {
        print("a = \(a), b = \(b). a and b are not nil")
    } else if let a = a {
        print("a = \(a). b is nil")
    } else if let b = b {
        print("b = \(b). a is nil")
    } else {
        print("a and b are nil")
    }
}
func update() {
    print("no parameters")
}

update()                //  "no parameters\n"
update(a: nil, b: nil)  //    "a and b are nil\n"
update(a: nil, b: "Y")  // "b = Y. a is nil\n"
update(a: "X", b: nil)  // "a = X. b is nil\n"
update(a: "X", b: "Y")  // "a = X, b = Y. a and b are not nil\n"

答案 2 :(得分:0)

也尝试写这样的东西:

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")

这是更实用的方式