Wednesday, February 20, 2019

Lesson 4 - Object

Copy in to Playground
func show(){
print("This is example text")
}
show()
class example{
func multiply(a:Int, b:Int)->Int{
let c=a*b
return c
}
}
Run to see the text "This is example text"

Class example done nothing here.
Add these line to Playground.
var obj =  example()
let so=10
let so2=12
obj.multiply(so,b:so2)

We ‘ve just create and use object.
The line var obj =  example() create object obj of class example.
Connect object with method in class by a dot, we can access any method in class.
When we make app, if need to use a method in many class, we don’t need to copy method to all class, just create an object of holder class and we can use any method inside it.
Create new class name example2
class example2{
func sum(a:Int,_ b:Int)->String {
let c=a+b
return"Result is " + String(c)
    }

}
var obj2 =  example2();
obj2.sum(so,so2)

Object is the way we use a class, try to create other method and access them by use object.
Now you can understand what is a class, it open with class ClassName{ end with }
That ‘s very simple and easy. Don’t just read definitions in programme books, let code something and you will understand all concepts.

No comments:

Post a Comment