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

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
主站蜘蛛池模板: 若羌县| 巴南区| 阳朔县| 南通市| 松江区| 伊金霍洛旗| 瓦房店市| 高雄县| 麻江县| 鞍山市| 清远市| 普兰店市| 砚山县| 桓台县| 尉犁县| 曲阳县| 瑞安市| 巫山县| 庆城县| 砀山县| 宜黄县| 行唐县| 萝北县| 罗田县| 上林县| 威海市| 尼木县| 唐山市| 理塘县| 晋城| 交口县| 通辽市| 商都县| 阿拉尔市| 岢岚县| 鄂伦春自治旗| 仙桃市| 张家港市| 黄浦区| 武川县| 霍林郭勒市|