此次作業為第二個作業《swift類的屬性與方法》的補充,照常,先貼要求
定義gender列舉
//性別的列舉
enum gender: int
}
定義department列舉
//公寓的列舉
enum department
定義schoolprotocol協議
//學校協議
protocol schoolprotocol
func lendbook()
}
定義person類並例項化
//人類
class person: customstringconvertible
}//構造方法
init(firstname: string, lastname: string, age: int, gender: gender)
convenience init(firstname: string, age: int, gender: gender)
convenience init(firstname: string)
required convenience init()
//過載==
static func ==(lhs: person, rhs: person) -> bool
//過載!=
static func !=(lhs: person, rhs: person) -> bool
//實現customstringconvertible協議中的計算屬性,可以使用print直接輸出物件內容
var description: string
//輸出person *** is running
func run()
}var p1 = person(firstname: "張")
var p2 = person(firstname: "張", age: 20, gender: .male)
print(p1) //輸出fullname: 張, age: 0, gender: male
print(p1 == p2) //輸出false
print(p1 != p2) //輸出true
定義teacher類並例項化
//教師類
class teacher: person, schoolprotocol
init(title: string, department: department)
convenience required init()
//重寫父類的計算屬性
override var description: string
//過載父類run方法
override func run()
//遵循協議的方法
func lendbook()
}var t1 = teacher(title: "hello", department: .one)
print(t1) //輸出title: hello, fullname: , age: 0, gender: unknow, department: one
定義student類並例項化
//學生類
class student: person, schoolprotocol
init(stuno: int, department: department)
required convenience init()
//重寫父類的計算屬性
override var description: string
//過載父類run方法
override func run()
//遵循協議的方法
func lendbook()
}var s1 = student(stuno: 2015110101, department: .two)
print(s1) //輸出stuno: 2015110101, fullname: , age: 0, gender: unknow, department: two
對陣列執行操作
//初始化乙個空的person陣列
var array = [person]()
//生成5個person物件
for i in
1...5 //生成3個teacher物件
for i in
1...3 //生成4個student物件
for i in
1..<5
//定義乙個字典,用於統計每個類的物件個數
var dict = ["person": 0, "teacher": 0, "student": 0]
foritem
in array else
ifitem is student else
}//輸出字典值
for (key, value) in dict
//原始陣列
print("------------------------------")
foritem
in array
//根據age從大到小排序
print("------------------------------")
array.sort
foritem
in array
//根據全名從前往後排序
print("------------------------------")
array.sort
foritem
in array
//根據gender和age從大往小排序
print("------------------------------")
array.sort
foritem
in array
//窮舉,呼叫run方法和lendbook方法
print("------------------------------")
foritem
in array else
if let student = item
as? student
}
最終執行的結果:
swift 列舉 結構 類
enum animal 可以編譯器可以推斷出右邊的型別。點可以省略 var ani animal bird switch ani 可以給列舉值成員賦值 enum animal var ani animal dog 3,bigdog switch ani enum animal int 通過列舉的ra...
swift入門第三季(列舉,類,物件導向, 協議)
列舉形式 enum 列舉名關聯值 enum plantclass user set newvalue 構造器 init first string,last string let s user first 極客 last hello print s.fullname s.fullname 測試 測試2...
Swift協議中類繼承協議的mutating問題
之前實際開發的時候遇到的乙個小問題,網上也沒有找到相關說明。本來當時弄明白了想著記下來的,但是比較忙就耽擱了,趁今天休息記錄一下。首先,我們看一下下面這個兩數之和的協議 protocol test customstringconvertible varnum2 intfunc getsum intf...