Old_SWIFT(221012)/함수이야기

<Filter> 함수 더하기 추론(조금...)

KataRN 2021. 11. 12. 15:56
반응형

안녕하세요. KataRN입니다.

 

오늘은 Filter 함수에 대해 알아보겠습니다.

관련있는듯없는사진.gif

 

공식문서부터 알아보겠습니다.

filter(_:)

Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.

Declaration

func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]

Parameters

isIncluded

A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array.

Return Value

An array of the elements that isIncluded allowed.

Discussion

In this example, filter(_:) is used to include only names shorter than five characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"

오늘도 애플 공식 예제는 뭔가 부족하군요...

그래서 오늘도 제가 준비했습니다.

let arr = [1,2,3,4,5,6,7,8,9,10]
let odd = arr.filter({ (value: Int) -> Bool in
    return (value % 2 != 0)
})
print(odd)
//012345678910

기본 배열에서 홀수만 골라낸 것입니다.

filter 함수는 배열에서 "특정 조건에 해당하는 것만 가져와줘"라는 뜻입니다.

좀더 쉽게 말하자면 filter 뒤에 특정 조건식을 넣고 참인경우에만 가져오게 되는 것입니다.

 

여기서 추론을 이용해 코드를 줄여보겠습니다.

let odd = arr.filter({value in value % 2 != 0})

한번 더 줄여보겠습니다.

let odd = arr.filter({$0 % 2 != 0})

한번더?

let odd = arr.filter{$0 % 2 != 0}
//괄호생략

 

 

 

최종적으로 아래의 코드가 되는 것입니다.

let arr = [1,2,3,4,5,6,7,8,9,10]
let odd = arr.filter{$0 % 2 != 0}
print(odd)
//012345678910

 

 

 

코테기준으로 말씀드리자면 이또한 코드는 간결해지지만 코드의 효율성은 떨어집니다.

오늘도 글을 읽어주셔서 감사합니다.

 

반응형