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

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").

主站蜘蛛池模板: 云和县| 化德县| 徐汇区| 柳河县| 松原市| 日喀则市| 西乌| 托克托县| 化州市| 广宁县| 望奎县| 广平县| 高密市| 深水埗区| 江城| 周口市| 印江| 柘城县| 高雄县| 利川市| 克拉玛依市| 乐至县| 九台市| 德兴市| 驻马店市| 阿勒泰市| 乌什县| 锡林浩特市| 二手房| 靖江市| 广水市| 望城县| 四川省| 延吉市| 林西县| 通辽市| 贵德县| 时尚| 丰顺县| 漳州市| 安新县|