swift tutorial 2

15

Click here to load reader

Upload: jintin-lin

Post on 12-Apr-2017

180 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Swift Tutorial  2

Swift Tutorial - 2Jintin

Page 2: Swift Tutorial  2

Function

• Code block

• Function Name

• Parameter

• Return value

Page 3: Swift Tutorial  2

Hello World Again

func sayHello(personName: String) -> String { let greeting = "Hello, " + personName + "!"

return greeting }

Page 4: Swift Tutorial  2

Default Valuefunc someFunction(parameterWithDefault: Int = 12) { // function body goes here // if no arguments are passed to the function call, // value of parameterWithDefault is 12 } someFunction(6) // parameterWithDefault is 6 someFunction() // parameterWithDefault is 12

Page 5: Swift Tutorial  2

Tuplefunc minMax(array: [Int]) -> (min: Int, max: Int) { var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) }

Page 6: Swift Tutorial  2

Closure

• Code block

• no Name

• Parameter

• Return value

Page 7: Swift Tutorial  2

Structure

{ (parameters) -> return type in statements }

Page 8: Swift Tutorial  2

Sort 1

func backwards(s1: String, _ s2: String) -> Bool { return s1 > s2 }

var reversed = names.sort(backwards)

Page 9: Swift Tutorial  2

Sort 2

reversed = names.sort({ (s1: String, s2: String) -> Bool in return s1 > s2 })

Page 10: Swift Tutorial  2

Sort 3

reversed = names.sort( { s1, s2 in return s1 > s2 } )

Page 11: Swift Tutorial  2

Sort 4

reversed = names.sort( { s1, s2 in s1 > s2 } )

Page 12: Swift Tutorial  2

Sort 5

reversed = names.sort( { $0 > $1 } )

Page 13: Swift Tutorial  2

Sort 6

reversed = names.sort(>)

Page 14: Swift Tutorial  2

Closure Parameter

func sample(closure: () -> Void) { // function body goes here }

Page 15: Swift Tutorial  2

Trailing Closure

sample({ // closure's body goes here }) sample() { // trailing closure's body goes here } sample { // trailing closure's body goes here }