티스토리 뷰

반응형

 

☑️  dynamic-callable 간단 설명 

 

@dynamicCallable 은 객체가 함수처럼 동작할 수 있도록 만들어준다. 

쉽게 말하면, 해당 객체에 대해 함수 호출 연산자 ()를 사용할 수 있게 해준다. 

이를 통해 동적으로 호출되는 동작을 구현할 수 있다.

어떤 객체의 호출을 일반화하거나, 다양한 유형의 인자를 처리하는 등의 상황에서 유용하다. 

 

 

[1] 수학연산 

@dynamicCallable
struct DynamicMultiplier {
    func dynamicallyCall(withArguments args: [Int]) -> Int {
        return args.reduce(1, *)
    }
}

let multiplier = DynamicMultiplier()
multiplier(1, 10) // 10
multiplier(2, 3, 4, 5) // 120

 

 

[2] 로그찍기 

@dynamicCallable
struct Logger {
    func dynamicallyCall(withArguments args: [Any]) {
        for arg in args {
            print(arg)
        }
    }
}

let logger = Logger()
logger(true)
logger(200, ["key": "value"])
logger(1, 3.14, ["a", "b", "c"])

 

ㄴ GPT 는 Printer 라고 네이밍 했는데, 이게 더 명확한 것 같기도.. 

 

[3] 유연한 API 호출

@dynamicCallable
struct APIRequest {
    func dynamicallyCall(withKeywordArguments args: KeyValuePairs<String, Any>) {
        // API 요청 보내는 로직
        for (key, value) in args {
            print("\(key): \(value)")
        }
    }
}

let request = APIRequest()
request(endpoint: "https://api.example.com", method: "GET", params: ["key": "value"])

 

 

[4] Fluent Interface 

@dynamicCallable
struct FluentInterface {
    func dynamicallyCall(withArguments args: [String]) -> FluentInterface {
        print("Called with arguments: \(args)")
        return self
    }
}

let builder = FluentInterface()
builder("command1")("command2")("command3")

 

 

ㄴ GPT 가 이것도 FluentInterface 라 했으나 솔직히 잘 모르겠음. 

 

플루언트 인터페이스는 
메서드 체이닝(메서드가 해당 객체를 반환하고 나서 반환된 객체를 다시 호출하는 식으로 여러 메서드를 한번에 호출하는 기법)을 
기반으로 코드가 쉬운 영어 문장으로 보이게끔 가독성을 향상시키는 API 설계 기법이다.

에릭 에반스와 마틴 파울러가 고안했다. 
https://martinfowler.com/bliki/FluentInterface.html

 

정의상 맞는 것 같지만, 가독성이 향상되었다고 볼 수 있을까? 

builder.command1().command2()  가 일반적으로 말하는 fluentInterface 인 것 같은데.. 

 

 

반응형
댓글