官术网_书友最值得收藏!

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
主站蜘蛛池模板: 武冈市| 土默特左旗| 微山县| 博客| 天峻县| 白河县| 沅陵县| 瑞昌市| 兴隆县| 辰溪县| 天长市| 中西区| 荃湾区| 桂林市| 尼玛县| 土默特左旗| 新乡市| 开化县| 宁强县| 中山市| 武夷山市| 苏尼特右旗| 临桂县| 平陆县| 石嘴山市| 应城市| 莎车县| 双牌县| 渭源县| 普陀区| 进贤县| 石河子市| 香河县| 绥化市| 乃东县| 玉溪市| 织金县| 平谷区| 东乌| 宁晋县| 武威市|