Swift 函數重載
當兩個或更多函數具有相同的名稱但不同的參數時,它們被稱為重載函數,這個過程被稱為函數重載。愛掏網 - it200.com
讓我們假設一個情況。愛掏網 - it200.com您需要開發一個射擊游戲,玩家可以使用刀、手榴彈和槍攻擊敵人。愛掏網 - it200.com讓我們看看您對攻擊功能的解決方案可能如何定義這些動作為函數:
示例
func attack() {
//..
print("Attacking with Knife")
}
func attack() {
//..
print("Attacking with Blade")
}
func attack() {
//..
print("Attacking with Gun")
}
你可以看到上面的程序對編譯器來說是混亂的,當你在Swift中執行這個程序時,你會得到一個 編譯時錯誤,“attack()”在這里之前已經被聲明過了。愛掏網 - it200.com然而,另一個解決辦法可能是為這個特定功能定義不同的函數名:
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 來創建物理對象,如Knife,Grenade和Gun。愛掏網 - it200.com上面的示例還存在一個問題,就是我們必須記住不同函數的名字,才能調用特定的攻擊動作。愛掏網 - it200.com為了解決這個問題,使用了函數重載,即不同函數的名字相同,但傳入的參數不同。愛掏網 - it200.com
使用函數重載的相同示例
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
程序解釋
在上面的程序中,創建了三個不同的函數,它們的名稱都是“attack”。愛掏網 - it200.com它們接受不同的參數類型,通過這種方式,在不同的條件下調用這個函數。愛掏網 - it200.com
- 調用attack(with: Gun())觸發函數func attack(with weapon:Gun)中的語句。愛掏網 - it200.com
- 調用attack(with: Grenade())觸發函數func attack(with weapon:Grenade)中的語句。愛掏網 - it200.com
- 調用attack(with: Knife())觸發函數func attack(with weapon:Knife)中的語句。愛掏網 - it200.com
使用不同參數類型進行函數重載
示例:
func output(x:String) {
print("Welcome to \(x)")
}
func output(x:Int) {
print(" \(x)")
}
output(x: "Special")
output(x: 26)
輸出:
Welcome to Special
26
在上面的程序中,這兩個函數具有相同的名稱 output() 和相同數量的參數,但參數類型不同。愛掏網 - it200.com第一個output()函數以字符串作為參數,而第二個output()函數以整數作為參數。愛掏網 - it200.com
- 對output(x: “Special”)的調用觸發函數func output(x:String)中的語句。愛掏網 - it200.com
- 而對output(x: 26)的調用則觸發函數func output(x:Int)中的語句。愛掏網 - it200.com
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。