simple things that compose(簡單事物的有效組合)
函數(shù)function:執(zhí)行特定任務的一段代碼。將功能模塊化,是代碼復用的重要手段。
函數(shù)四要素:函數(shù)名,參數(shù),返回值,函數(shù)體(功能)
func add(a: Int, b: Int) -> Int {
a + b
}
var result1: Int = add(a: 3, b: 5)
print(result1)
// Prints "8"
重載overload:函數(shù)名稱相同,形參列表不同或者返回值類型不同。
是的,Swift區(qū)別C++/Java返回值不同也是重載。
- 參數(shù)不同
func add(a: Int) -> Int {
a + 1
}
var result2 = add(a: 3)
print(result2)
// Prints "4"
- 返回值不同
func add(a: Int, b: Int) -> String {
"\(a) + \(b) = \(a + b)"
}
var result3: String = add(a: 3, b: 5)
print(result3)
// Prints "3 + 5 = 8"
為了區(qū)分重載,需在定義變量/常量的時候顯示聲明類型。類型推導編譯會報Ambiguous use of 'add(a:b:)'