Rodrigo Ruiz
Rodrigo Ruiz

Reputation: 4355

Swift - check if function parameter was passed

Let's say I have the following function:

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

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

And I can call it in those ways (expecting to do as in the comments):

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

How can I achieve this?

EDIT:

The only way I could think of doing this is with method overload, but that is unfeasible when you have many parameters (don't even have to be that many, 4 will already need 17 methods).

Upvotes: 2

Views: 2118

Answers (3)

Leo Dabus
Leo Dabus

Reputation: 236458

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"

Upvotes: 2

Arsen
Arsen

Reputation: 10951

Also try to write something like this:

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

It's more functional way

Upvotes: 0

Aderstedt
Aderstedt

Reputation: 6518

I'm not sure why you would want to do this, but you can do it in this way:

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

Upvotes: 2

Related Questions