struct Grade {
var letter: Character
var points: Double
var credits: Double
}
class Person {
var firstName: String
var lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
func printMyName() {
print("My name is \(firstName) \(lastName)")
}
}
class Student: Person {
var grades: [Grade] = []
}
let jay = Person(firstName: "Jay", lastName: "Lee")
let jason = Student(firstName: "Jason", lastName: "Lee")
jay.firstName // Jay
jason.firstName // Jason
jay.printMyName() // Person
jason.printMyName() // Student
let math = Grade(letter: "B", points: 8.5, credits: 3)
let history = Grade(letter: "C", points: 6, credits: 2)
jason.grades.append(math) // [{letter "B", points 8.5, credits 3}]
jason.grades.append(history) // [{letter "B", points 8.5, credits 3}, {letter "C", points 6, credits 2}]
jason.grades.count // 2
// 학생인데 운동선수
class StudentAthelete : Student {
var minimumTrainingTime: Int = 2
var trainedTime: Int = 0
func train() {
trainedTime += 1
}
}
// 운동선수인데 축구선수
class FootballPlayer: StudentAthelete {
var footballTeam = "FC Swift"
override func train() {
trainedTime += 2
}
}
// Person > Student > Athelete > FootballPlayer
var athelete1 = StudentAthelete(firstName: "Yuna", lastName: "Kim")
var athelete2 = FootballPlayer(firstName: "HeungMin", lastName: "Son")
athelete1.firstName // "Yuna"
athelete2.firstName // "HeungMin"
athelete1.grades.append(math) // [{letter "B", points 8.5, credits 3}]
athelete2.grades.append(math) // [{letter "B", points 8.5, credits 3}]
athelete1.minimumTrainingTime // 2
athelete2.minimumTrainingTime // 2
//athelete1.footballTeam
athelete2.footballTeam // "FC Swift"
athelete1.train()
athelete1.trainedTime // 1
athelete2.train()
athelete2.trainedTime // 2
athelete1 = athelete2 as StudentAthelete // as를 사용하여 어퍼캐스팅
athelete1.train()
athelete1.trainedTime // 4
if let son = athelete1 as? FootballPlayer { // as?를 사용하여 다운캐스팅
print("--> team:\(son.footballTeam)") // "--> team:FC Swift\n"
}
::public/Swift