Setting the same value for a few quick parameters

I have a function like this:

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

I would like someone to be able to set both of these options if they want to. But if they set only the first parameter, I would like to saveURL = documentURL. Is there a way to do this in a function declaration?

+7
function swift swift2
source share
3 answers

It is not possible to do this in the function declaration itself, however you can do it on the same line of the function body using an optional parameter with the default value nil and nil coalescing operator .

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

The advantage of this method is that saveURL is not optional inside the function body, which eliminates the need to use the force reversal operator later.

+1
source share

In Swift 2.3, 3:

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

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 } } 
+1
source share

All Articles