Toy Project/Swift Language Syntax

6. Swift Closure basic

개발자킹콩 2021. 1. 21. 16:37

// Closure : 이름이 없는 메소드라고 생각하면 된다.
// (Int, Int) -> Int : 클루져의 타입
var multiply1: (Int, Int) -> Int = { (a:Int, b:Int) -> Int in
  return a * b
}

// 여기서 간략하게 쓸 수 있다.
// a, b는 Int로 들어올 것이고, 반환도 Int로 한다고 type을 지정했다.
var multiply2: (Int, Int) -> Int = { a, b in
  return a * b
}

// 그리고 들어오는 파라미터의 index를 나타낼 수 있다.
var multiply3: (Int, Int) -> Int = { return $0 * $1 }

var multiplyClosure: (Int, Int) -> Int = { $0 * $1 }

print(multiplyClosure(4,2))
//너무 빡세게 줄이면 의미전달이 안될 수 있으니 multiply2정도가 적당


// Closure의 장점을 잘 보여주는 함수를 만들려한다.
// 두 수와 연산자를 받는 Closure를 정의해보자
func operateTwoNum(a: Int, b: Int, operation: (Int, Int) -> Int) -> Int {
  let result = operation(a, b)
  return result
}
print(operateTwoNum(a: 4, b: 3, operation: multiply2))

var addClosure: (Int, Int) -> Int = {a,b in return a + b}
print(operateTwoNum(a: 4, b: 3, operation: addClosure))

// 함수 호출문에서 바로만들기
print(operateTwoNum(a:4, b:3) { a, b in 
  return a - b
})

// Closure는 이름 없는 메소드다
// 실무에서 parameter와 Closure를 받는 함수가 많은데, 그때그때 원하게 동작하는 Closure를 정의할 수 있다.





// Capturing Values
// 지역변수의 경우 자신의 scope에서만 유효한 변수이다.
// 하지만 Closure에 의해 capture된 변수는 외부에서도 사용할 수 있게된다.

let voidClosure: ()-> Void = {
  print("IOS 개발자 클로져 사랑해")
}
voidClosure()

var count = 0
let incrementer = {
  count += 1
}

incrementer()
incrementer()
incrementer()
incrementer()
print(count)


'Toy Project > Swift Language Syntax' 카테고리의 다른 글

8. Swift Structure  (0) 2021.01.21
7. Swift Closure 조금더  (0) 2021.01.21
5. Swift Collection(Dicionary, Set)  (0) 2021.01.21
4. Swift Collection (Array)  (0) 2021.01.21
3. Swift Optional  (0) 2021.01.21