上QQ阅读APP看书,第一时间看更新
Default arguments
Function parameters maybe given default values, in the following form:
func paintFace(color: String = "white")
{
print("I have painted my face \(color)")
}
It's probably clear already that the function can be called with color, or with none, in which case the default value is used:
paintFace()
paintFace(color: "red")
If we run the code above, we'll see the following output:
I have painted my face white
I have painted my face red
This can also be used with optional type parameters. This allows us to test for the presence of an argument to the function:
func paintWagon(color: String? = nil)
{
if let color = color {
print("I have painted the wagon \(color)")
}
}