- Swift 4 Programming Cookbook
- Keith Moon
- 187字
- 2021-07-08 10:21:24
Default parameter values
One convenience in Swift is that you can specify default values for parameters, which allows you to omit the parameter when calling. Let's take the preceding example situation, where we are creating a contact app to hold information about our family and friends. Many of your family members are likely to have the same family name as you, so you can set your family name as the default value for that parameter so that you only need specify the family name if it is different from the default.
Let's enter the following code into a playground:
func fullName(givenName: String, middleName: String, familyName: String = "Moon") -> String {
return "\(givenName) \(middleName) \(familyName)"
}
Defining a default value looks similar to assigning a value to the familyName: String = "Moon" parameter. When calling the function, the parameter with the default value does not have to be given:
let keith = fullName(givenName: "Keith", middleName: "David")
let alissa = fullName(givenName: "Alissa", middleName: "May")
let laura = fullName(givenName: "Laura", middleName: "May", familyName: "Jones")
print(keith) // Keith David Moon
print(alissa) // Alissa May Moon
print(laura) // Laura May Jones
推薦閱讀
- C語言課程設計
- Instant Ext.NET Application Development
- Keras深度學習實戰
- PySpark Cookbook
- Terraform:多云、混合云環境下實現基礎設施即代碼(第2版)
- Practical Microservices
- Learning iOS Security
- Hacking Android
- Instant Automapper
- Scrapy網絡爬蟲實戰
- 從零開始構建深度前饋神經網絡:Python+TensorFlow 2.x
- SQL Server實例教程(2008版)
- Laravel Design Patterns and Best Practices
- JavaWeb從入門到精通(視頻實戰版)
- MATLAB計算機視覺實戰