Swift Review#20[方法method-實體方法(instance method)、型別方法(type method)]

--

前言

繼上篇文章談到所謂的屬性後,可以了解struct、class中有屬性也有方法,而方法這個東西,大致在概念上一分爲二:實體方法型別方法

  • 實體方法(instance method):先需要生成一個特定型別(類別、結構或列舉)的實體,才能使用這個實體裡的方法。
  • 型別方法(type method):屬於特定型別(類別、結構或列舉)本身的方法。

正文

1.實體方法

實體方法需要做的事情,就是先在類別或結構裡面詳述方法內含什麼:

然後,再以生成實體的方式,用實體去呼叫設定好的方法。

而一般而言,一個值型別(結構或列舉)實體的屬性,不能在它的實體方法中被修改,所以,以下會介紹Mutating 作為如果遇到特殊情形下,可以使用Mutating作為方法的修改。

Mutating methods

100 Days of Swift-Mutating method的相關描述:

The problem is that when you create the struct Swift has no idea whether you will use it with constants or variables, so by default it takes the safe approach: Swift won’t let you write methods that change properties unless you specifically request it.

翻譯翻譯:當你創建 struct 時,Swift 不知道你是將它與常量還是變量一起使用,所以在默認情況下它將採用一個安全的方法:除非你特別要求,否則 Swift 不會讓你編寫改變屬性的方法。

When you want to change a property inside a method, you need to mark it using the mutating keyword,

所以,當你需要改變一個方法裡面的屬性的時候,你需要標示”Mutating”

Swift起步走的相關描述:

一般情況下,一個值型別(結構或列舉)實體的屬性不能在它的實體方法中被修改。但如果有特殊需求需要修改屬性,可以使用變異(mutating)這個方法。要使用變異方法,將關鍵字mutating放在方法的func之前就可以了,如下:

我們在這邊使用mutating func ,可以讓原先的屬性內容被改變

或許這裡有更好的例子:

這邊如果用mutating func的話,就會讓someone的內容跟之前的預設去做改變,可能要體會一下。

2.型別方法

形別方法有別於實體方法,為定義在特定型別(類別、結構與列舉)上的方法,它不是屬於實體,而是屬於這個型別(類別、結構與列舉)上的方法。

什麼意思呢?

可以這樣說,就是class裡面有class func ,所以它不是一種實體。

或是用static func來做也是可行的。

總之,型別方法不需要生成實體,就可以直接呼叫型別方法,因為型別方法是屬於一個特定型別(類別、結構與列舉)而非一個實體

綜合上述,我們討論到三件事情,一是實體方法的使用,它必須經過實體話,才能以實體.方法( )的方式來呼叫,而型別方法因為本身的構成是類別、結構裡面含有型別方法,所以只要在外部將類別.型別方法( ),拿出來使用就可以了。

而變異方法Mutating func則是在實體方法中,假若要在定義過的實體外部進行更動的話,就可以在類別、結構內部先設置一個變異方法,然後在外部套用,就會變成Mutating func所指定的內容。

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

影山小麥機
影山小麥機

Written by 影山小麥機

本職為Mobile工程師,熱愛分享視野,也樂意站在ChatGPT的肩膀上。訂閱小麥機,收割技術、職涯、人生的難題。

No responses yet

Write a response