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?
In Swift 2.3, 3:
func stamp(documentURL: NSURL, saveURL: NSURL?) {
var saveURL = saveURL
if saveURL == nil {
saveURL = documentURL
}
}
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With