- Swift 4 Programming Cookbook
- Keith Moon
- 197字
- 2021-07-08 10:21:24
Parameter overloading
Unlike Objective-C, Swift supports parameter overloading, which allows for functions to have the same name and only be differentiated by the parameters that they take.
Let's learn more about parameter overloading by entering the following code into a playground:
func combine(_ givenName: String, _ familyName: String) -> String {
return "\(givenName) \(familyName)"
}
func combine(_ integer1: Int, _ integer2: Int) -> Int {
return integer1+integer2
}
let combinedString = combine("Finnley", "Moon")
let combinedInt = combine(5, 10)
print(combinedString) // Finnley Moon
print(combinedInt) // 15
Both the preceding functions have the name combine, but one takes two Strings as parameters and the other takes two Ints. Therefore, when we come to call the function, the compiler knows which implementation we intended by the values we pass as parameters.
We've introduced something new in the preceding function declarations--anonymous parameter labels, _ givenName: String.
When we declare the parameters, we use an underscore _ for the parameter label; this indicates that we don't want a parameter name shown when calling the function. This should only be used if the purpose of the parameters is clear without the labels, as is the case in the preceding example--combine("Finnley", "Moon").
- Flink SQL與DataStream入門、進階與實戰
- 編寫高質量代碼:改善Python程序的91個建議
- INSTANT Sencha Touch
- Vue.js 3.0源碼解析(微課視頻版)
- Swift 3 New Features
- 單片機應用技術
- Advanced Oracle PL/SQL Developer's Guide(Second Edition)
- Mastering Android Development with Kotlin
- Julia高性能科學計算(第2版)
- Android應用案例開發大全(第二版)
- PHP+Ajax+jQuery網站開發項目式教程
- 細說Python編程:從入門到科學計算
- ActionScript 3.0從入門到精通(視頻實戰版)
- 物聯網系統架構設計與邊緣計算(原書第2版)
- 3D Printing Designs:Octopus Pencil Holder