Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

sanichdaniel의 iOS 개발 블로그

Pure functions in swift 본문

swift

Pure functions in swift

sanich8355 2020. 10. 14. 21:16

Pure function 이란?

1. 같은 인자라면, 같은 리턴 값 (외부에 의존하지 않는다)

2. 사이드 이펙트가 없다

장점

1. 재사용성, 테스트하기 쉬위짐

2. 사이드 이펙트가 적음

함수를 pure하게 만들기

1. 값을 바꾸지 말고, 새로운 값을 리턴하자

extension String {
    mutating func addSuffixIfNeeded(_ suffix: String) {
        guard !hasSuffix(suffix) else {
            return
        }

        append(suffix)
    }
}

아래 함수는 값을 mutate 하기에 pure 하지 않다

mutable 값에만 호출할수 있게되고 더러운 var muate assign 코드가 필요해진다.

var fileName = contentName
fileName.addSuffixIfNeeded(".md")
try save(content, inFileNamed: fileName)
extension String {
    func addingSuffixIfNeeded(_ suffix: String) -> String {
        guard !hasSuffix(suffix) else {
            return self
        }

        return appending(suffix)
    }
}

2. 외부 값에 의존하지 말고, 인자로 받자

func makeFailureHelpText() -> String {
    guard numberOfAttempts < 3 else {
        return "Still can't log you in. Forgot your password?"
    }
    
    return "Invalid username/password. Please try again."
}

func makeFailureHelpText(numberOfAttempts: Int) -> String {
    guard numberOfAttempts < 3 else {
        return "Still can't log you in. Forgot your password?"
    }
    
    return "Invalid username/password. Please try again."
}

Purity 강제하기

value 타입으로 로직을 구성하기

value 타입은 mutating 키워드를 붙이지 않는이상 mutable state를 갖지 못한다.

mutable하게 만드는 과정에서 mutating 키워드를 붙이게 되고, 이것은 pr 리뷰에서 발견이 가능하다!

struct PriceCalculator {
    let shippingCosts: ShippingCostDirectory
    let currency: Currency

    func calculateTotalPrice(for products: [Product],
                             shippingTo region: Region) -> Cost {
        let productCost: Cost = products.reduce(0) { cost, product in
            return cost + product.price
        }

        return productCost.convert(to: currency)
    }
}

 

 

출처

www.swiftbysundell.com/articles/pure-functions-in-swift/

www.swiftbysundell.com/articles/functional-networking-in-swift/

 

'swift' 카테고리의 다른 글

Operator Overloading  (0) 2020.10.16
빌드 타임 개선  (0) 2020.10.14
일급 시민 함수 - swift  (0) 2020.10.14
Identifiable  (0) 2020.10.07
Hashable  (0) 2020.10.07