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

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

主站蜘蛛池模板: 临江市| 新巴尔虎右旗| 海淀区| 贵阳市| 长沙县| 阜新市| 黄浦区| 武邑县| 赞皇县| 同心县| 重庆市| 开封市| 芮城县| 义马市| 阿拉善左旗| 永靖县| 莎车县| 永泰县| 涪陵区| 顺义区| 伊川县| 揭阳市| 措勤县| 新巴尔虎右旗| 大宁县| 集贤县| 绥阳县| 新竹市| 苏州市| 凤城市| 乡宁县| 克拉玛依市| 溆浦县| 英德市| 濮阳市| 开阳县| 崇州市| 巫溪县| 永兴县| 平度市| 远安县|