Wednesday, February 20, 2019

Lesson 1 - Variable, constant

Register an account, download Xcode.
Open Xcode, File > New > Playground, enter a name, screen look like this

We code on left panel, on right, Xcode auto run to show result. You can press triangle blue button at bottom left to make it run immediately.
Copy in to playground.
let str2="First string"
var concat=str+str2

We call str, str2, concat are variables, the line var str=”Hello, playground” declare a variable.
Let mean constant, we can’t assign or change value like var.
Type continue
str2="next"

An red mark appear, move cursor to it, Xcode say can’t assign value to str2, need change to var, double click to fix it, let str2 will change to var str2.
Continue.
let a=8
let b=10
var sum=a+b
Xcode auto recognize data type, we always use let or var for any data type.
Type two cross before line var tong=a+b, it become comment.
We comment to know what we did, next day easy to remember.
Continue
let text=”8
let sum=b+text
Xcode show error mark because text is String, can’t sum with integer.
All characters in quotation mark will be consider as String.
To change a String to number, we use:
let number=Int(String)
Copy to continue.
if(a>b){
            sum=10
}
else{
            sum=100
}
Run to see result 100.

Now delete else command, run, screen show 18.
We see the different of if has else and no else.
If has else, when if not true, command go to else, value will be 100. I no else, age still remain value 27, value of a+b.
Continue.
var c=0
for i in0..<5 {
c=c+i
}
c
Xcode show result 5 times and number 10. For loop use to repeat a command, here we sum number from 0 to 5.
Add if command in to for.
if(i%2==0)
Character % % character mean divide and get remainder.
We sum all even numbers from 0-5.
Result equalt 6, which mean 2 + 4.
Change to if(i%2==1), result equalt 4, mean 1 + 3.
Here if has no else, because we don’t care about other numbers.
Continue
var d=1.8
var e=d/7
Run too see decimal number.

More practical with * and /
Excercise
Use for loop to sum even or odd number from 1-100.

No comments:

Post a Comment