我剛剛開始使用Swift,並且進入了課堂。如果我想要一個名爲「Team」的超級類和一個名爲「Player」的「Team」的子類。Swift的超級初始問題
我的想法是創建一個團隊和一個玩家,然後將玩家添加到teamPlayers Array。但是當我創建我的球員時,我必須重新創建球隊名稱。沒有辦法覆蓋Player類的init方法?
類(球員是球隊的一個子類): - 團隊 - 玩家
import UIKit
class Team {
var teamName: String
var teamPlayers:[Player] = []
init(aName: String){
self.teamName = aName
}
// methods
func addPlayer(aPlayer: Player){
teamPlayers.append(aPlayer)
}
}
class Player: Team {
var playerName: String
var playerNumber: Int
init(aName: String, aNumber: Int){
self.playerName = aName
self.playerNumber = aNumber
super.init(aName: "Barcelona")
}
}
var myTeam: Team = Team(aName: "Barcelona")
var lionelMessi: Player = Player(aName: "Lionel Messi", aNumber: 10)
myTeam.addPlayer(lionelMessi)
更新:
讓更多喜歡這個意義上說,這就是我努力實現:
import UIKit
class Team {
var teamName: String
var teamPlayers:[Player] = []
init(aName: String){
self.teamName = aName
}
// methods
func addPlayer(aPlayer: Player){
teamPlayers.append(aPlayer)
}
func returnCount() -> Int {
return self.teamPlayers.count
}
}
class Player: Team {
var playerName: String
var playerNumber: Int
init(aName: String, aNumber: Int, aTeam: String){
self.playerName = aName
self.playerNumber = aNumber
super.init(aName: aTeam)
}
}
var myTeam: Team = Team(aName: "Barcelona")
var lionelMessi: Player = Player(aName: "Lionel Messi", aNumber: 10, aTeam: myTeam.teamName)
myTeam.addPlayer(lionelMessi)
var daniAlvez: Player = Player(aName: "Dani Alvez", aNumber: 2, aTeam: myTeam.teamName)
myTeam.addPlayer(daniAlvez)
myTeam.returnCount()
無論如何,爲什麼'Player'是Team'的一個子類呢?這似乎沒有太大意義。總之,你在做什麼* *是重寫構造... – sapi 2014-09-10 23:26:05
沒關係, 修正了這一點: '類球員:球隊{VAR playerName:字符串 VAR playerNumber:詮釋 的init(aName:串,aNumber的:中等,ATEAM:串){ self.playerName = aName self.playerNumber = aNumber的 super.init(aName:ATEAM) } } VAR myTeam:團隊=小組(aName:「巴塞羅那「) var lionelMessi:Player = Player(aName:」Lionel Mess我「,a編號:10,aTeam:myTeam.teamName) myTeam.addPlayer(lionelMessi)' – outime 2014-09-10 23:29:16
@sapi你會怎麼做? – outime 2014-09-10 23:30:59