[APP開發-使用Swift]觀念介紹: Class、Object

Chiwen Lai
4 min readSep 28, 2017

--

介紹Class、Object之前,我們從OOP(Object Oriented Programming)開始。

Objects are like people. They’re living, breathing things that have knowledge inside them about how to do things and have memory inside them so they can remember things. And rather than interacting with them at a very low level, you interact with them at a very high level of abstraction, like we’re doing right here. ~Steve Jobs

在物件導向的程式世界中,我們嘗試能夠逼真地模擬真實世界,讓程式設計工作更視覺化,更好理解。例如我們描述『人』這個Class的時候,我們可以嘗試描述如下:

  • 姓名、髮色、身高、體重,這些統稱為屬性(properties),
  • 要描述某一個特定的人,必須要制定以上4個屬性,因此我們加上初始化事件(Events),為了區分屬性名稱及參數名稱,我們使用self來表示Class的屬性。
  • 人會做的動作,我們制定了jump跳躍這個method

如此一來,我們定義好『人』這個抽象類別,就可以很容易地製造人的物件(Objects),也就是個別的人。

let charlie = Person(name: "Charlie", hairColor: "Black", height: 132, weight: 28)let tom = Person(name: "Tom", hairColor: "Brown", height: 176, weight: 75)let mary = Person(name: "Mary", hairColor: "Blond", height: 166, weight: 55)

Class Person是抽象的,Object charlie、Object tom、Object mary才是實體。

所以真正的實體才可以跳躍,但抽象的Person.jump()是會出錯的!

charlie.jump()  --> Charlie is jumping.

回到我們的餐廳class Restaurant,我們定義好餐廳這個類別需要的屬性之後,我們就可以很容易地宣告多個餐廳。

var restaurants:[Restaurant] = [Restaurant(name: "義大皇家酒店星亞自助餐", type: "餐廳", location: "840高雄市大樹區學城路1段153號義大皇家酒店LB大廳樓層", phone: "07-6568166#21205", image: "edaroyal.jpg", isVisited: false),Restaurant(name: "義大皇家酒店皇樓", type: "港式飲茶餐廳", location: "840高雄市大樹區學城路1段153號義大皇家酒店LB大廳樓層", phone: "07-6568166#21402", image: "royal.jpg", isVisited: false),Restaurant(name: "皇港茶餐廳", type: "餐廳", location: "827高雄市燕巢區義大路1號", phone: "07-6150011", image: "restaurant.jpg", isVisited: false),Restaurant(name: "叁合院", type: "臺菜餐廳", location: "840高雄市大樹區學城路1段12號A區5樓", phone: "07-6568222", image: "sanhoyan.jpg", isVisited: false),Restaurant(name: "1010湘料理", type: "湘菜餐廳", location: "840高雄市大樹區學城路1段12號A區5樓", phone: "07-6569009", image: "1010.jpg", isVisited: false),]

如此restaurants就可以依照Restaurant定義放多個我們喜愛的餐廳。是不是很方便呢?

<<<6. UITableView Basic Cell

--

--