클로저는 람다와 비슷, 같다고 볼수 있다

 

 

클로저를 왜 쓰는가...

함수내에 조건이 들어있으면 함수를 호출할때 함수를 들여다 보기전까지 조건이 어떻게 되어 있는지 모른다

 

장점 :

1. 조건을 클로저로 사용할 경우에는 함수를.호출할때 알수 있다.

2. 조건 변경시 조건만 새로만들어서 넣어주면 됨

3. 시간절약, 오류 최소화, 코드파악 용이

 

단점 :

1. 로직이 한눈에 알아보기 쉽지 않다

 

함수안에 조건이 있을경우 

- 조건을 추가할 경우가 생길때 파라미터를 또 추가하고 기존에 함수를 호출한 부분을 또 수정 해야되기때문 불편

 

결론: 조건이 여러가지일 경우에는 조건을 클로로 받아 구현하는것이 코드가 깔끔하고 확인하기도 편하다

 

var names = ["apple", "lemon", "brown", "red", "band", "candy"]

func filterString(datas: [String], firstString: String) -> [String] {
    var newDatas = [String]()
    
    for idx in 0..<datas.count {
        if datas[idx].first?.description == firstString {
            newDatas.append(datas[idx])
        }
    }
    return newDatas
}

func filterStringClosure(datas: [String], closure: (String) -> Bool) -> [String]{
    
    var newDatas = [String]()
    
    for data in datas {
        if closure(data) {
            newDatas.append(data)
        }
    }
    return newDatas
}

let returnValue = filterStringClosure(datas: names) { element -> Bool in
    if element.first?.description == "b" {
        return true
    }
    
    return false
}

var findA: (String) -> Bool = { element in
    if element.first?.description == "a" {
        return true
    }
    return false
}

var findB: (String) -> Bool = { element in
    if element.first?.description == "b" {
        return true
    }
    return false
}

var findLength5: (String) -> Bool = { element in
    if element.count == 5 {
        return true
    }
    return false
}

filterString(datas: names, firstString: "a")
filterString(datas: names, firstString: "b")
filterStringClosure(datas: names, closure: findA)
filterStringClosure(datas: names, closure: findB)
filterStringClosure(datas: names, closure: findLength5)

 

'swift > 잡다함' 카테고리의 다른 글

Struct VS Class  (0) 2021.06.16
extension, protocol, Higher_Order_Func  (0) 2021.06.16
ARC (weak, unowned)  (0) 2021.06.01
mutating  (0) 2021.02.17
lazy  (0) 2021.02.17

+ Recent posts