Consider the following code
class Truck { var speed = 0 func accelerate() { speed += 10 if speed > 80 { speed = 80 } printSpeed() } func accelerateBy(quantum: Int) { speed += quantum if speed > 80 { speed = 80 } printSpeed () } func accelerateBy(quantum: Int, repeat:Int) { for index in 1...repeat { speed += quantum if speed >= 80 { speed = 80 break } printSpeed () } printSpeed () } func decelerate() { speed -= 10 if speed<0 { speed = 0 } printSpeed() } func stop() { while speed>0 { decelerate () } } func printSpeed() { print("Speed: \(speed)") } }
To call the first method, you need to pass in an integer argument:
c.accelerateBy(5)
To call the second method, you need to pass in an integer value for the first and second arguments, and in addition you need to specify the external parameter name for the second argument:
c.accelerateBy (5, repeat: 10)
In Swift, the first parameter in a method is a local parameter name by default, while subsequent parameters are both local and external parameter names.
If you want to make the first parameter an external parameter name, prefix it with the hash (# ) tag, as shown here:
func accelerateBy(# quantumm : Int, repeat:Int) {
...
}
You now need to specify the external parameter name for the first argument:
c.accelerateBy( quantum: 5, repeat:10)
If you do not wish the second or subsequent parameter names to be exposed as external parameter names, prefix the parameter name with an underscore (_):
func accelerateBy (quantum: Int, _ repeat: Int) {
...
}
You now don't have to specify the external parameter name for the second argument:
c.accelerateBy(5, 10 )
class Truck { var speed = 0 func accelerate() { speed += 10//from w ww . j a va2 s . co m if speed > 80 { speed = 80 } printSpeed() } func accelerateBy(quantum: Int) { speed += quantum if speed > 80 { speed = 80 } printSpeed () } func accelerateBy(quantum: Int, repeat:Int) { for index in 1...repeat { speed += quantum if speed >= 80 { speed = 80 break } printSpeed () } printSpeed () } func decelerate() { speed -= 10 if speed<0 { speed = 0 } printSpeed() } func stop() { while speed>0 { decelerate () } } func printSpeed() { print("Speed: \(speed)") } } var c = Truck () c.accelerateBy(5, 10 ) c.printSpeed()