[iOS Coding] 定義兩個類別, 用到繼承, 類別裡包含屬性和方法。 然後用類別生出物件 存取物件的屬性和呼叫物件的方法 —Playground
Published in
4 min readNov 28, 2018
定義類別並包含屬性和方法
class playGround{var height = "under 150cm"var ticketCost: Int = 20func adultTicket(){ ticketCost = ticketCost * 2 print(ticketCost) }func childrenTicket(){ ticketCost = ticketCost / 3 print(ticketCost) }}var myChildren = playGround()var myGrandpa = playGround()myGrandpa.height = "above 150cm"print("My Children's height is " + myChildren.height)print("My Grandpa's height is " + myGrandpa.height)myChildren.childrenTicket()myGrandpa.adultTicket()myGrandpa.adultTicket()
定義兩個類別並使用繼承
class playGround{var height = "under 150cm"var ticketCost: Int = 20 func adultTicket(){ ticketCost = ticketCost * 2 print(ticketCost) } func childrenTicket(){ ticketCost = ticketCost / 3 print(ticketCost) }}class playGroundForMore: playGround {var additionalFee = 10 func morePeople(){ additionalFee = additionalFee + 20 print(additionalFee) }
}
var oneCouple = playGroundForMore()var fivePeopleFamily = playGroundForMore()print("The Entrance Fee for One Coupple is ")//這裡特別強調因為Couple是兩個人,所以原先的ticketCost: Int = 20這個要乘以2,所以多出以下這一行非常“人工”的寫法,但是這一行經過討教彼得潘大大原先是希望透過下面的 fucntion 回傳再做運算的程式去拿到 func adultTicket()運算得結果後再乘以Couple的兩個人得到屬於Couple的最新票價,但最下方的程式碼研究未果所以作罷,只好等上課的時候在專心聽講了....oneCouple.ticketCost = 20 * 2oneCouple.adultTicket()print("The Additional Fee for Family is ")fivePeopleFamily.morePeople()
以下為研究不出來也不知道怎麼套用的程式碼 Orz|||// 定義函式 有一個型別為 Int 的參數以及一個型別為 Int 的返回值// 函式的功能是將帶入的參數加十 並返回func addTen(number: Int) -> Int {let n = number + 10// 使用 return 來返回值 這個返回值的型別要與上面標註的相同return n}// 呼叫函式 傳入整數 12 會返回 22let newNumber = addTen(number: 12)// 印出:22print(newNumber)