6์ผ์ฐจ: 100DaysOfSwift๐Ÿš€

1648 ๋‹จ์–ด

6์ผ์ฐจ



ํ์‡„ ํŒŒํŠธ 1



Swift์—์„œ ํด๋กœ์ €๋Š” ํ•จ์ˆ˜ ์ด๋ฆ„์ด ์—†๋Š” ํŠน๋ณ„ํ•œ ์œ ํ˜•์˜ ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.

์˜ˆ์‹œ

let Sau = {
    print("I'm Saurabh, iOS developer")
}

//call the Closure
Sau()


2.ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ํด๋กœ์ €

์šฐ๋ฆฌ๋Š” ํด๋กœ์ €๋ฅผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด func ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋‹ค์Œ์€ ํด๋กœ์ €๋ฅผ ์„ ์–ธํ•˜๋Š” ๊ตฌ๋ฌธ์ž…๋‹ˆ๋‹ค.

{ (parameters) -> returnType in
   // statements
}
Here,


๋งค๊ฐœ๋ณ€์ˆ˜ - ํด๋กœ์ €์— ์ „๋‹ฌ๋œ ๋ชจ๋“  ๊ฐ’
returnType - ํด๋กœ์ €๊ฐ€ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฐ’์˜ ์œ ํ˜•์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.
in (์„ ํƒ ์‚ฌํ•ญ) - ๋งค๊ฐœ๋ณ€์ˆ˜/returnType์„ ํด๋กœ์ € ๋ณธ๋ฌธ์—์„œ ๋ถ„๋ฆฌํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ

์˜ˆ์‹œ

let Sau={ (name:String) in
print("MySelf \(name)")
}

//Call the Closure
Sau("Saurabh")


ํด๋กœ์ €์˜ ๋ฐ˜ํ™˜ ๊ฐ’



ํด๋กœ์ €๊ฐ€ ์–ด๋–ค ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ํ•˜๋ ค๋ฉด ๋ฐ˜ํ™˜ ์œ ํ˜•์„ ์–ธ๊ธ‰ํ•˜๊ณ  return ๋ฌธ์„ ์‚ฌ์šฉํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด,

/ closure definition
var findSquare = { (num: Int) -> (Int) in
  var square = num * num
  return square
}

// closure call
var result = findSquare(3)

print("Square:",result)


๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ํ์‡„



ํด๋กœ์ €๋Š” ๋ฌธ์ž์—ด ๋ฐ ์ •์ˆ˜์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ ํ•จ์ˆ˜์— ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

let driving = {
    print("I'm driving in my car")
}

func travel(action: () -> Void) {
    print("I'm getting ready to go.")
    action()
    print("I arrived!")
}

travel(action: driving)


ํ•ด๋‹น ํด๋กœ์ €๋ฅผ ํ•จ์ˆ˜์— ์ „๋‹ฌํ•˜์—ฌ ํ•ด๋‹น ํ•จ์ˆ˜ ๋‚ด์—์„œ ์‹คํ–‰ํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๋ ค๋ฉด ๋งค๊ฐœ ๋ณ€์ˆ˜ ์œ ํ˜•์„ () -> Void๋กœ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค. ์ฆ‰, "๋งค๊ฐœ ๋ณ€์ˆ˜๋ฅผ ํ—ˆ์šฉํ•˜์ง€ ์•Š๊ณ  Void๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค"๋ฅผ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค. Swift์˜ "nothing"์„ ๋งํ•˜๋Š” ๋ฐฉ์‹์ž…๋‹ˆ๋‹ค.

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ