Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting the same value for multiple swift parameters

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?

like image 361
Tom J Avatar asked Aug 30 '16 22:08

Tom J


3 Answers

In Swift 2.3, 3:

func stamp(documentURL: NSURL, saveURL: NSURL?) {
     var saveURL = saveURL
     if saveURL == nil {
         saveURL = documentURL
     } 
}
like image 140
pedrouan Avatar answered Oct 19 '22 19:10

pedrouan


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.

like image 1
Hamish Avatar answered Oct 19 '22 19:10

Hamish


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
    } 
}
like image 1
Marco Santarossa Avatar answered Oct 19 '22 20:10

Marco Santarossa