用 ChatGPT 舉例 — 學習 Swift 的類別
Published in
4 min readDec 11, 2022
用 swift 定義電影類別,包含屬性和方法,不要寫 init
class Movie {
var title: String = ""
var director: String = ""
var releaseYear: Int = 0
func showInfo() {
print("Title: \(title)")
print("Director: \(director)")
print("Release Year: \(releaseYear)")
}
}
let movie = Movie()
movie.title = "The Shawshank Redemption"
movie.director = "Frank Darabont"
movie.releaseYear = 1994
movie.showInfo()
定義一個繼承 Person 的類別,包含屬性和方法,方法要跟 Person 不一樣
ps: ChatGPT 的回答有點問題,以下範例做了一些調整。
class Person {
var name: String = ""
var age: Int = 0
func showInfo() {
print("Name: \(name)")
print("Age: \(age)")
}
}
class Student: Person {
var studentId: String = ""
func study() {
print("\(name) is studying.")
}
}
let person = Student()
person.name = "John Doe"
person.age = 20
person.studentId = "123456"
person.showInfo()
person.study()
用 swift 定義電影類別,包含屬性和方法
class Movie {
var title: String
var director: String
var releaseYear: Int
init(title: String, director: String, releaseYear: Int) {
self.title = title
self.director = director
self.releaseYear = releaseYear
}
func showInfo() {
print("Title: \(title)")
print("Director: \(director)")
print("Release Year: \(releaseYear)")
}
}
let movie = Movie(title: "The Shawshank Redemption", director: "Frank Darabont", releaseYear: 1994)
movie.showInfo()
請以機械鍵盤為例說明 Swift 的繼承
當我們談到繼承時,可以想像成機械鍵盤的設計。機械鍵盤有許多種類,但是它們都有一些共通的特性,例如:按下按鍵會有觸感、按下按鍵會有聲音等等。這些特性可以想像成是機械鍵盤的父類別,而不同種類的機械鍵盤則可以想像成是子類別。子類別可以繼承父類別的特性,並且可以加入自己的特性。在 Swift 中,我們可以使用 class 關鍵字來定義一個類別,並使用 : 來繼承父類別。以下是一個簡單的範例:
class MechanicalKeyboard {
var hasTactileFeedback = true
var hasAudibleFeedback = true
func pressKey() {
// do something
}
}
class CherryMXKeyboard: MechanicalKeyboard {
var hasRGBLighting = true
var hasCustomizableKeycaps = true
override func pressKey() {
super.pressKey()
// do something else
}
}
在這個範例中,MechanicalKeyboard 是父類別,CherryMXKeyboard 是子類別。CherryMXKeyboard 繼承了 MechanicalKeyboard 的 hasTactileFeedback 和 hasAudibleFeedback 屬性,並且加入了自己的 hasRGBLighting 和 hasCustomizableKeycaps 屬性。此外,CherryMXKeyboard 也覆寫了 pressKey() 方法,並在方法中呼叫了父類別的 `press。