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

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
主站蜘蛛池模板: 玉林市| 敖汉旗| 广元市| 临沧市| 东乌| 轮台县| 永济市| 纳雍县| 永宁县| 垫江县| 井研县| 保靖县| 义马市| 兴文县| 盱眙县| 白城市| 乌苏市| 泸西县| 香港 | 兴山县| 阿克苏市| 汉川市| 霍林郭勒市| 黄大仙区| 天门市| 包头市| 峨眉山市| 珲春市| 清涧县| 七台河市| 奉节县| 禄丰县| 宜兰市| 从化市| 洛浦县| 河池市| 岐山县| 革吉县| 白玉县| 图木舒克市| 鸡东县|