Reputation: 115
Can i set up function with optional input parameter? that means when i call that function, i can either pass the parameter or not to pass the parameter.
Upvotes: 1
Views: 3261
Reputation: 262504
Yes, you can supply a default parameter value, in which case you can leave the parameter off at the call site:
func someFunction(someParam: Int = 12) {
print(someParam)
}
someFunction(10)
someFunction()
You can combine this with Optional
to default to nil
:
func someFunction(someParam: Int? = nil) {
if let x = someParam {
print(x)
}
else {
print("no param given")
}
}
Parameters with default values should be placed at the end of the parameter list.
Upvotes: 8