ielyamani
ielyamani

Reputation: 18591

Is there a way to know if a parameter (with a default value) has been passed to a function in Swift?

Here is a function in Swift

func flexStrings2 (s1 : String = "", s2 :String = "") -> String {
   return s1 + s2 == "" ? "none" : s1 + s2
}

flexStrings2() // returns "none"
flexStrings2(s1: "Hello!") // returns "Hello!"
flexStrings2(s1: "What's ", s2: "up?") // returns "What's up?"
flexStrings2(s1: "", s2: "") // returns "none"

I am trying to write a function called flexStrings2() in Swift that meets the following requirements:

I want flexStrings2(s1: "", s2: "") to return "" and not "none"

can this be done done in one line of code in the function body?

This is an ugly solution:

func flexStrings2 (s : String...) ->String{
     return s.count == 0 ? "none" : s.count > 2 ? "Maximum 2 parameters" : s.reduce("", combine: {$0 + $1})
}

Plus it doesn't conform to the syntax for calling flexStrings2.

So is there a way to know if a parameter (with a default value) has been passed to a function in Swift?

Upvotes: 1

Views: 529

Answers (2)

kasplat
kasplat

Reputation: 1187

This doesn't meet the challenge because it can take zero to many String arguments, but otherwise I think it does what was intended and is easier to read by using a Variadic parameter.

func flexStrings(s: String...) -> String {
    return s.count == 0 ? "none" :  join("", s)
}

https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

func flexStrings(s1: String = "", s2: String = "") -> String {
    return s1 + s2 == "" ? "none": s1 + s2
}

Is the "answer" for Challenge #2 from...

http://www.raywenderlich.com/76349/swift-ninja-part-1

The challenge is trying to illustrate the use of default values, but it doesn't get into optional parameter values and the use of nil.

The answer undetected provided is probably more technically correct, but that's a kind of optional nightmare of ? and ! I hope we don't see a lot of in Swift and made more difficult to read because of the use of the nested ternary operators. The criticism is not towards undetected, but rather picking out ? and ! in Swift source.

Upvotes: 0

undetected
undetected

Reputation: 484

Swift recommends the use of nil to indicate that a variable has no value. You can use this to distinguish between no value being passed and a blank value being passed, which seems necessary because you want to differentiate between the two.

func flexStrings2 (s1 : String? = nil, s2 :String? = nil) -> String {
    return (!s1 && !s2) ? "none" : (s1 ? s1! : "") + (s2 ? s2! : "")
}

flexStrings2() // returns "none"
flexStrings2(s1: "Hello!") // returns "Hello!"
flexStrings2(s1: "What's ", s2: "up?") // returns "What's up?"
flexStrings2(s1: "", s2: "") // returns "" like you wanted

Upvotes: 4

Related Questions