Swift 函數(shù)重載
當(dāng)兩個(gè)或更多函數(shù)具有相同的名稱但不同的參數(shù)時(shí),它們被稱為重載函數(shù),這個(gè)過(guò)程被稱為函數(shù)重載。愛(ài)掏網(wǎng) - it200.com
讓我們假設(shè)一個(gè)情況。愛(ài)掏網(wǎng) - it200.com您需要開(kāi)發(fā)一個(gè)射擊游戲,玩家可以使用刀、手榴彈和槍攻擊敵人。愛(ài)掏網(wǎng) - it200.com讓我們看看您對(duì)攻擊功能的解決方案可能如何定義這些動(dòng)作為函數(shù):
示例
func attack() {
//..
print("Attacking with Knife")
}
func attack() {
//..
print("Attacking with Blade")
}
func attack() {
//..
print("Attacking with Gun")
}
你可以看到上面的程序?qū)幾g器來(lái)說(shuō)是混亂的,當(dāng)你在Swift中執(zhí)行這個(gè)程序時(shí),你會(huì)得到一個(gè) 編譯時(shí)錯(cuò)誤,“attack()”在這里之前已經(jīng)被聲明過(guò)了。愛(ài)掏網(wǎng) - it200.com然而,另一個(gè)解決辦法可能是為這個(gè)特定功能定義不同的函數(shù)名:
struct Knife {
}
struct Grenade {
}
struct Gun {
}
func attackUsingKnife(weapon:Knife) {
//..
print("Attacking with Knife")
}
func attackUsingGrenade(weapon:Grenade) {
//..
print("Attacking with Grenade")
}
func attackUsingGun(weapon:Gun) {
//..
print("Attacking with Gun")
}
在上面的示例中,你們使用了 struct 來(lái)創(chuàng)建物理對(duì)象,如Knife,Grenade和Gun。愛(ài)掏網(wǎng) - it200.com上面的示例還存在一個(gè)問(wèn)題,就是我們必須記住不同函數(shù)的名字,才能調(diào)用特定的攻擊動(dòng)作。愛(ài)掏網(wǎng) - it200.com為了解決這個(gè)問(wèn)題,使用了函數(shù)重載,即不同函數(shù)的名字相同,但傳入的參數(shù)不同。愛(ài)掏網(wǎng) - it200.com
使用函數(shù)重載的相同示例
struct Knife {
}
struct Grenade {
}
struct Gun {
}
func attack(with weapon:Knife) {
print("Attacking with Knife")
}
func attack(with weapon:Grenade) {
print("Attacking with Grenade")
}
func attack(with weapon:Gun) {
print("Attacking with Gun")
}
attack(with: Knife())
attack(with: Grenade())
attack(with: Gun())
輸出:
Attacking with Knife
Attacking with Grenade
Attacking with Gun
程序解釋
在上面的程序中,創(chuàng)建了三個(gè)不同的函數(shù),它們的名稱都是“attack”。愛(ài)掏網(wǎng) - it200.com它們接受不同的參數(shù)類型,通過(guò)這種方式,在不同的條件下調(diào)用這個(gè)函數(shù)。愛(ài)掏網(wǎng) - it200.com
- 調(diào)用attack(with: Gun())觸發(fā)函數(shù)func attack(with weapon:Gun)中的語(yǔ)句。愛(ài)掏網(wǎng) - it200.com
- 調(diào)用attack(with: Grenade())觸發(fā)函數(shù)func attack(with weapon:Grenade)中的語(yǔ)句。愛(ài)掏網(wǎng) - it200.com
- 調(diào)用attack(with: Knife())觸發(fā)函數(shù)func attack(with weapon:Knife)中的語(yǔ)句。愛(ài)掏網(wǎng) - it200.com
使用不同參數(shù)類型進(jìn)行函數(shù)重載
示例:
func output(x:String) {
print("Welcome to \(x)")
}
func output(x:Int) {
print(" \(x)")
}
output(x: "Special")
output(x: 26)
輸出:
Welcome to Special
26
在上面的程序中,這兩個(gè)函數(shù)具有相同的名稱 output() 和相同數(shù)量的參數(shù),但參數(shù)類型不同。愛(ài)掏網(wǎng) - it200.com第一個(gè)output()函數(shù)以字符串作為參數(shù),而第二個(gè)output()函數(shù)以整數(shù)作為參數(shù)。愛(ài)掏網(wǎng) - it200.com
- 對(duì)output(x: “Special”)的調(diào)用觸發(fā)函數(shù)func output(x:String)中的語(yǔ)句。愛(ài)掏網(wǎng) - it200.com
- 而對(duì)output(x: 26)的調(diào)用則觸發(fā)函數(shù)func output(x:Int)中的語(yǔ)句。愛(ài)掏網(wǎng) - it200.com