Overloading in Swift

Tuesday, June 28, 2016 A.D.

You can overload functions in Swift. Let's try it!

1
2
3
4
5
6
7
8
9
10

funcmyFunction(item:String)->String{return"Here is that string: \(item)"}funcmyFunction(item:Int)->String{return"And here is that integer: \(item)"}myFunction("Hi there")\\"Here is that string: Hi there"myFunction(4)\\"And here is that integer: 4"

Neat! Swift knows which version of the function we want based solely on the type of the parameter we pass in. We can even write two versions of this function that take the same type of parameter (or parameters) as long as they have different return types.

Wait! We got an error on that last line! Xcode is complaining about an "Ambiguous use
of 'yesterday'". This is because Xcode can't tell which version of our function
we want. There's not enough information there. We need to supply the type we
are expecting like so:

1

letdate:NSDate?=yesterday(today)

Now date holds an object of type NSDate?. We can safely use functions that
differ only in return type in places where one of those types are expected as
well. Observe:

That last line will return the string "SMASH 12-06-2015". I'm not specifying
the return type of yesterday anywhere, but since Swift wants a string in that
spot, it knows to just go ahead and use the version that returns a string.