函式的外部參數(External Parameter Names)
範例程式碼:
func calculateArea(width:Float, height:Float) ->Float{
return width * height
}
print(calculateArea(width: 20, height: 30))
//得到結果600
加上外部參數withWidth及andHeight
func calculateArea(withWidth width:Float, andHeight height:Float) ->Float{
return width * height
}
print(calculateArea(withWidth: 20, andHeight: 30))
//得到結果600
注意: 如果你提供了外部參數名,那麼函式在被呼叫時,必須使用外部參數名。
Q:為何沒有寫外部參數名,程式也可以執行?
A:因為Xcode自動幫你把外部參數名,設成跟內部參數名一樣。
空的外部參數
func shopping(_ thing1:String, thing2:String){
//底線"_"代表沒有外部值
print("i want to buy \(thing1) and \(thing2)")
}
shopping("dumping", thing2: "steak")
因為有時候寫程式,會遇到呼叫函式時,不用寫外部參數名的時候。