Wednesday, February 20, 2019

Lesson 6 – Global variable, local variable

A declaration variable has valid inside open and close bracket contain it.
Copy in to Playground.
let number=10
func f(){
  
    print("Value of number is:"+String(number))
}
f()
Screen show number 10.

Now add this line inside f().
var number=8

Now  screen show 8, variable number in function f() and number outside are different, the outsider call global variable, insider call local variable.
A variable declare after Class open bracket will be global variable, it will colored green. Local variables will have black color.
Add this line to below.
let b=number+5

Screen show 15, this number variable has green color. Local variable only valid in it ‘s open and close bracket, here is function f().
Make the line let number=10 become comment.

Xcode show error in number, because variable number inside f() can’t be use outside it ‘s bracket area. It has black color mean local variable.
Now remove comment, type b on to bottom, both number and b have green color, they are global variables, error disappear.

When start to learn programme you should not name local variable the same with global variable to avoid mistaken when use them later.

When declare a new variable, if it color blue we know it is global variable, no need to see brackets.

No comments:

Post a Comment