[동계 모각코] [3회차] 클로저와 고차함수

MoonGoon·2023년 1월 21일
0

동계모각코

목록 보기
4/13
post-thumbnail
  • 클로져 - 클로저와 함수는 같은거에요?

    개인적인 생각: 클로저 사용시 in은 왜 있는가?

    The start of the closure’s body is introduced by the in keyword. This keyword indicates that the definition of the closure’s parameters and return type has finished, and the body of the closure is about to begin.

    Because the body of the closure is so short, it can even be written on a single line:

    reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 > s2 } )

    This illustrates that the overall call to the sorted(by:) method has remained the same. A pair of parentheses still wrap the entire argument for the method. However, that argument is now an inline closure.

    Swift 공식문서에 있는 내용인데, 요약하자면 클로저는 매우 짧으므로 in 키워드를 사용함으로써 클로저 파라미터의 정의와, 리턴 으로 끝난다고 알려주는 키워드정도로 생각하면 될듯 싶다.

  • 클로저 - 클로저를 언제 왜 쓸까요?

    • 여러 함수가 공통점이 많고 차이가 거의 없을때 클로저를 사용하면 하나로 만들 수 있다!

    • ex)

      func sumTwoNumber( _ first: Int, _ second: Int) -> String {
      	return String(first + second)
      }
      func minusTwoNumber( _ first: Int, _ second: Int) -> String {
      	return String(first - second)
      }
      func multipleTwoNumber( _ first: Int, _ second: Int) -> String {
      	return String(first * second)
      }

      위 함수들은 사칙연산을 제외하면 매개변수로 받는 인자도 같고, 반환값도 같다! 위 함수를

      func calculateNumber( _ first: Int, _ second: Int, calculate: (Int, Int) -> Int) -> String { return String(calculate(first, second)) }

      라는 함수 하나로 선언해놓으면 나중에

      result = calculateNumber(13, 4, calculate: { first, second in return first **+** second })  // 13 + 4 인 17이 저장됨 사칙연산만 바꿔주면 그에맞게 처리함

      로 사용할 수 있다.

      코드를 설명하자면 calculateNumber 함수가 인자를 받는데, Int 값 두 개와 closure하나해서 총 3개를 인자로 받고 클로저는 Int값 두 개를 받아서 Int값을 리턴해주는데, 이를 String으로 감싼게 이 함수의 리턴값이 된다. 그렇기에 함수를 사용할 때 클로저 내부의 사칙연산값만 바꾸어주면 그에 맞는 연산값이 출력이 된다.

  • 클로저 - 트레일링 클로저란?

    • 함수의 마지막 인자가 클로저라면 파라미터 이름을 생략할 수 있다!!
  • 고차함수 - 함수를 입력받는 함수

    • 매개변수로 함수를 받아오는 함수!
    • eg.
      • map

        ```swift
        let ages = [13, 32, 11, 39]
        
        ForEach(ages.map({ item in
        	String(item) }) , id: \.self) { age in Text(age) }
        ```

        위 예시의 경우 Text는 String만 가능한데, map 함수를 사용해 ages 원소들을 String으로 전처리 한 값을 ForEach문에서 출력

      • filter

        ```swift
        let ages = [13, 32, 11, 39]
        
        ForEach(ages.filter({ item in
        	item % 2 == 0
        	}).map({ item in
        			String(item) }) , id: \.self) { age in Text(age) }
        ```

        위 예시는 filter 함수를 사용해 짝수만 출력하게 됨

      • reduce

        • 데이터들을 조건에 맞추어 줄여서 하나만 남도록 함

          let ages = [1, 3, 5, 7]
          ages.reduce(1, {partialResult, next in  // 1이 초기값, partial이 현재 인덱스, next가 다음 인덱스
          	partialResult * next }) // 105 출력
          	// 위 조건을 수행한 후 다시 partialResult에 넣어줌
  • 고차함수 - 고차함수는 언제쓰나요? 왜 써요?

    • 반복문을 사용하는 함수를 한 번만 쓸 것 같으면 고차함수로 사용한다!
profile
Swift 개발자를 희망합니다

0개의 댓글