7

I have a function similar to this:

func stamp(documentURL: NSURL, saveURL: NSURL) {
        ...}

I'd like to be able to allow someone to set both of those parameters if they want. But if they only set the first parameter, I'd like saveURL = documentURL. Is there any way to do this in the function declaration?

3 Answers 3

3

In Swift 2.3, 3:

func stamp(documentURL: NSURL, saveURL: NSURL?) {
     var saveURL = saveURL
     if saveURL == nil {
         saveURL = documentURL
     } 
}
Sign up to request clarification or add additional context in comments.

2 Comments

It applies to Swift 2.3 too.
I guess there's no way to do this in the function declaration without code in the body?
1

There's no way to do this in the function declaration itself, however you can do it in a single line of the function body by using an optional parameter with a default of nil, and the nil coalescing operator.

func stamp(documentURL: NSURL, saveURL: NSURL? = nil) {
    let saveURL = saveURL ?? documentURL

    // ...
}

The advantage of doing it this way is that saveURL is non-optional within the function body, saving you from having to use the force unwrap operator later.

Comments

1

SWIFT 2

func stamp(documentURL: NSURL, var saveURL: NSURL? = nil) {
    if saveURL == nil {
        saveURL = documentURL
    } 
}

SWIFT 3

func stamp(documentURL: NSURL, saveURL: NSURL? = nil) {
    var saveURL = saveURL
    if saveURL == nil {
        saveURL = documentURL
    } 
}

4 Comments

Using var is discouraged in Swift functions as it will be removed in Swift 3. Just create a local variable with the same name.
@ozgur thanks I updated adding the swift 3 safe version
So, I guess there's no way to do in the function declaration?
@TomJ No, there is not

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.