Swift筆記:Global and Local Variables

外面的蘋果樹和自家花園的蘋果樹

Lumanman
Swift Things
5 min readOct 8, 2017

--

什麼是Global and Local Variables?

"Global variables are variables that are defined outside of any function, method, closure, or type context.
Local variables are variables that are defined within a function, method, or closure context."

-The Swift Programming Language (Swift 4)

翻譯年糕:

Global variables
=在function, method, closure, type context以所宣告的variables

Local variables
=在function, method, or closure context所宣告的variables

所以咧?為什麼要知道他們的分別?

因為global variables 和 local variables的scope是不一樣的!
Scope影響變數的可見度(visibility of variables)
所以要小心使用,不然程式會出現crash
例如在實作Xylophone App中:

會出現errors的情況:

1. playSelectedSound在UI Button中宣告為local variable
  1. playSelectedSound只在UI Button中可見,所以playSound function拿不到 playSelectedSound的value,出現 "unsolved Identifier"的error
  2. 在UI Button中沒有用到playSelectedSound的value,所以出現 "playSelectedSound was nerver used的警告

OR

2. playSelectedSound為local variables,但沒有要執行的值
  1. playSelectedSound為local variables,但沒有在UIbutton中填上playSound function要執行的值

OR

3. playSelectedSound為global variable

這看似沒有問題,但playSound function中playSelectedSound的值被定義為note3,所以不管按哪個鍵都只會播放note3這個音檔,這邊Xcode沒有跳出errors 是因為在程式的運作上沒有錯的地方,整個程式可以順利運行,只是不是我們預期的效果,所以在這個例子中,我們要找出問題所在便會需要一行行去看,推敲哪一行寫錯了,若有上千行程式的情況下便會十分費時費力。

Global and local variables正確的寫法

Global variable:在Class的一開始宣告(見第8行)

Local variable:用function的執行值宣告(見第13行)

該什麼時候用Global/Local variables?

從上面errors 的例子三可見global variable 若在不同function中有不同的值便很容易產生很難察覺的error,所以若是常數/不太會改動其值的variable便應盡量用global variable,因為這可以省掉不斷定義的功夫。但如果variable的值是常變的,如小木琴App中的playSelectedSound有七個不同的值,這便應該用local variable 以減低error的發生機率。

總結:

Global variables

  • 在function以外所宣告的variables
  • 在所在的Class的function都能使用

優點:

  1. 只需定義一次便整個Class都能使用 ∴很方便

缺點:

  1. 若出現了bug,很難找出哪裡有問題 ∵很多function都在用同一個variables

Local variables

  • 在function內所宣告的variables
  • 只能在該function中使用

優點:

  1. 出現了bug比較容易找出error breakpoint

缺點:

  1. 不能偷懶,每次都要定義

記憶小撇步:

外面的蘋果樹和自家的蘋果樹

Angela在她的課程中把Global and Local Variables比喻成種在外面的蘋果樹和種在自家花園的蘋果樹:

在自家園子裡的蘋果只有自家人才能拿得到,如果很多家都想吃蘋果的話,就要每家都種一棵蘋果樹,但一旦園子有蟲,就可以快速找出蟲蟲,因為花園的空間有限,種的樹也有限。相反;如果蘋果是種在外面的話,想吃的人就可以直接去拿,但如果有蟲害的話,就要找遍所有的樹才能找出蟲禍根源。

超好記!

--

--

Lumanman
Swift Things

Swift learner & sharer | Nothing is wasted, nothing is in vain.