Swift基礎:Class

王彤
王彤
Sep 4, 2018 · 3 min read

最近開始工作以後深刻感受到基本功的重要,於是有空就再重新學一次基礎,久沒更新,就把我對Class的認識跟大家分享吧!


Class的概念類似於物件的設計圖,例如我要蓋一棟全新的房子(物件),我就需要一個房子的設計圖(Class)。

如上圖,有了Class以後就能產生物件,只是我的Class裡面什麼屬性也沒有,所以產生出來的物件也是空的,什麼都沒有。


我可以在Class裡面增加一些屬性跟方法來描述我要產生的物件,每一個屬性都一定要有值,可以在宣告的時候就給它值,也可以在init方法給他值,如果你不想這麼早就塞值進去,可以跟我一樣用一個有參數的init方法(也可以用optional來處理)。

產生了物件以後,我就能使用Class裡的屬性以及方法。

init()代表產生物件時要執行的程式碼。
下面這一小段就是代表說物件產生的時候,我要把squareMeter這個參數塞進self.squareMeter這個屬性。

有的時候,我會想要用跟已經有的Class差不多的Class。

這樣講有點拗口,舉例來說就是我想要蓋一棟跟我之前蓋的房子差不多的房子。

我的AnotherBuilding繼承了Building,就算我沒有給AnotherBuilding任何屬性跟方法,產生出來的anotherBuilding也能使用Building的屬性及方法。

AnotherBuilding跟Building之間的關係:
我們會說AnotherBuilding是Building的子類別(subclass),Building是AnotherBuilding的父類別(superclass)。

我可以直接在AnotherBuilding裡面增加新的屬性跟方法,也可以修改原本就有的屬性跟方法。

如果要修改原本就有的屬性,再init方法裡面還要再super.init才能修改喔!
如果要修改原本就有的方法,可以用override。

To be continued……

Tung's iOS

紀錄Tung的iOS學習之路

王彤

Written by

王彤

Tung's iOS

紀錄Tung的iOS學習之路

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade