如何在 swift 中使用较少的参数创建闭包调用闭包

How to create closure calling closure with less parameters in swift

我正在尝试在 swift 中创建 class,它可以使用 0..N 个参数进行闭包,然后当调用具有 N 个参数的回调函数时,将仅传递所需的数量关闭。 我正在尝试这样做:

class CallbackImpl: AuthServiceLogoutCallback {
    private let callback: ((UUID, AuthServiceLogoutType) -> Void )?
    
    public init( cb: @escaping ((UUID, AuthServiceLogoutType) -> Void ))
    {
        callback = { cb( [=11=],  ) }
    }
    
    public init( cb: @escaping ((UUID) -> Void ))
    {
        callback = { cb( [=11=] ) }
    }
    
    public init( cb: @escaping (() -> Void ))
    {
        callback = { cb() }
    }
    
    public func onEvent(_ userId: UUID, type: AuthServiceLogoutType)
    {
        callback!( userId, type )
    }
}

第一个带有带两个参数的闭包的初始化没问题,带有带 1 和 0 参数的闭包的初始化给我错误表达式类型 '()' 在没有更多上下文的情况下不明确

做这种事情的正确方法是什么?

如果您提供更多关于正在使用和未使用的闭包参数的上下文,您可以实现您正在尝试的目标:

class CallbackImpl: AuthServiceLogoutCallback {
    private let callback: ((UUID, AuthServiceLogoutType) -> Void)?
    
    public init(cb: @escaping ((UUID, AuthServiceLogoutType) -> Void)) {
        callback = { cb([=10=], ) }
    }
    
    public init(cb: @escaping ((UUID) -> Void)) {
        callback = { uuid, _ in cb(uuid) }
    }
    
    public init(cb: @escaping (() -> Void)) {
        callback = { _, _ in cb() }
    }
    
    public func onEvent(_ userId: UUID, type: AuthServiceLogoutType) {
        callback!( userId, type )
    }
}