Declaration
func DoSomeWork(param1: String, param2: Int)
{
println("I saw \(param1) \(param2) times.")
}
// How to call
DoSomeWork("Sally", 3)
// Default Parameters
func DoSomeWork(param1: String, param2: Int = 2)
{
println("I saw \(param1) \(param2) times.")
}
// How to call
DoSomeWork("Sally")
// or
DoSomeWork("Sally", param2: 5)
// Note: With default parameters you HAVE to use the
// parameter name.
//Multiple Default Parameters
func DoSomeWork(name: String, howMany: Int=1, didSee: Bool=false)
{
if didSee {
println("I saw \(name) \(howMany) times.")
}
else {
println("I did not see \(name) at all.")
}
}
// How to call
DoSomeWork("Sally")
// or
DoSomeWork("Sally", didSee: true)
// or
DoSomeWork("Mark", didSee: true, howMany: 3)
// Notice how I can reorder the default parameters.
External Parameter Names
// Add extra argument info (called "argument labels")
// to help developers better understand what is happening
func DoSomeWork(forThisPerson param1: String, thisManyTimes param2: Int)
{
println("I worked for \(param1) \(param2) times.")
}
How to call
DoSomeWork(forThisPerson: "Sally", thisManyTimes: 3)
// Note: If you do not include the argument labels
// (external parameter names) you will get this issue:
// "Missing argument label 'thisManyTimes:' in call"
// One Parameter Name
// If you just want one parameter name but you still want
// to force developers to type it out when calling then
// you can use the pound (#) symbol in front of the parameter name.
func DoSomeWork(#forThisPerson: String, #thisManyTimes: Int)
{
println("I worked for \(forThisPerson) \(thisManyTimes) times.")
}
How to call
DoSomeWork(forThisPerson: "Sally", thisManyTimes: 3)
Return a variable
func ReturnVariable() -> Bool
{
return true
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.