Copy
in to Playground
func show(){
print("This is example text ")
}
Screen
show nothing.
Type
show() and run again.
Now
it show text as we want.
Copy
to continue.
func multiply(a:Int,_ b:Int){
let c=a*b
print("Result is: "+String(c))
}
Add
these line:
let so=10;
let so2=12;
multiply(so,so2)
Result
is 120.
The
codes name show(), multiply() call method or function.
The
line func multiply(a:Int,_ b:Int){ declare a
method, after that, we call to use.
Why need method ? When
coding, we use something many times, so we put them in a method, when use, we
simple call it.
Compare
show() and multiply() we see show() has nothing in it’s bracket, we say it not
receive parameters, multiply receive to integer numbers a, b.
If you delete dash before b in tinhnhan(), Xcode show error mark,
you must add b: to before so2
Copy to
below multiply()
func multiply2(a:Int, b:Int)->Int {
let c=a*b
return c
}
let so3=15;
let so4=2;
let d=multiply2(so3,so4)
print("Result is: "+String(d)).
Let
compare multiply() and multiply2(), we see arrow before int at
end of multiply2() different with multiply().
We say that multiply2() return a integer value. If method
return value, it must has return at end of method.
Method can return a
string, copy to below multiply2.
func add(a:Int,_ b:Int)->String {
let c=a+b
return"Result is " + String(c)
}
add(so3,so4)
Run
to see result.
Method can return
array, copy to continue.
func calculate(a:Int,_ b:Int)->[Int] {
var ar=[Int](count: 3, repeatedValue: 0)
let c=a+b;
let d=a-b;
let e=a*b;
ar[0]=c;
ar[1]=d;
ar[2]=e;
return ar
}
var ar=[Int](count: 3, repeatedValue: 0)
ar=calculate(so3,so4)
Run
to see result.
Method calculate()
return 3 numbers array result after calculate.
No comments:
Post a Comment