Function, Class

16

Click here to load reader

Transcript of Function, Class

Page 1: Function, Class

Function, ClassBy Akira Hirakawa

Page 2: Function, Class

Topics

• function

• class

Page 3: Function, Class

Function

// Chunks of Code func sayHello() { print("hello") }

Page 4: Function, Class

Function with parameters

func sayHello(name: String) { let greeting = "Hello, " + name + "!" print(greeting) } sayHello("Akira")

Page 5: Function, Class

Function with Multiple Parameters

func sayHello(name: String, from: String) { let greeting = "Hello, I'm \(name), from \(from)" print(greeting) } sayHello("Akira", from: "Japan")

Page 6: Function, Class

Function with return value

func sayHello(name: String) -> String { let greeting = "Hello, " + name + "!" return greeting } print(sayHello("Akira"))

Page 7: Function, Class

Function Parameter Names

func sayHello(name: String, from: String) { let greeting = "Hello, I'm \(name), from \(from)" print(greeting) } sayHello("Akira", from: “Japan")

• the first parameter omits external name

• second and subsequent parameters users local name as external name

Page 8: Function, Class

Specifying External Parameter Names

func sayHello(name localName: String, from: String) { let greeting = "Hello, I'm \(localName), from \(from)" print(greeting) } sayHello(name:"Akira", from: “Japan")

• write external param name before local param

Page 9: Function, Class

Omitting External Param Name

func sayHello(name: String, _ from: String) { let greeting = "Hello, I'm \(name), from \(from)" print(greeting) } sayHello("Akira", "Japan")

• write underscore before local name

Page 10: Function, Class

Default Parameter

func hello(name: String = "anonymous") { let greeting = "Hello, " + name + "!" print(greeting) } hello() hello("Singapore")

Page 11: Function, Class

Class

class SomeClass { }

blueprint of an object that contains information , behaviour

Page 12: Function, Class

Class can

• Define properties

• Define methods

Page 13: Function, Class

Properties, Methodsclass Person { var name: String var age: Int

// initialize init(name aName: String, age aAge: Int) { name = aName age = aAge } // instance method func walk() { } // class method class func hello() { } } Person(name: "Akira", age: 100).walk() Person.hello()

Page 14: Function, Class

Inheritance

class SomeClass { }

class SomeClass2: SomeClass { }

Page 15: Function, Class

Protocol

• to define a blueprint of methods, properties etc protocol GeekProtocol { func coding() -> Bool }

class SGGeek: GeekProtocol { func coding() -> Bool { print("coding coding coding") return true } }

Page 16: Function, Class

thanks