Swift - 使用 运行 时间参数选择器的补丁定义

Swift - patch definition with selector using run-time arguments

我正在尝试为使用 运行 时间参数功能但没有运气的程序集中的选择器创建补丁程序。有没有人解决过类似的问题或者它还不能使用 Swift?

汇编中的方法定义如下所示:

public dynamic func requestCodeApiGateway(phone: NSString) -> AnyObject {
    return TyphoonDefinition.withClass(RequestCodeApiGatewayImpl.self) { (definition) in
        definition.useInitializer("initWithApiService:apiRouter:phone:") { (initializer) in
            // ...
        }
    }
}

我正在这样创建 Patcher:

let patcher = TyphoonPatcher()
patcher.patchDefinitionWithSelector("requestCodeApiGatewayWithPhone:") { 
    // ...
}

P.S。部分使用 Objective-C 的解决方案也将受到赞赏

您似乎在 patchDefinitionWithSelector 中使用了错误的选择器。除了 init 之外,初始参数不会作为外部参数名称公开,也不包含在选择器中。

requestCodeApiGateway(NSString) 的选择器是 requestCodeApiGateway:

更新您的代码以使用该选择器应该可以解决问题:

patcher.patchDefinitionWithSelector("requestCodeApiGateway:") { 
    // ...
}

或者,您可以通过以下任一方式使选择器成为 requestCodeApiGatewayWithPhone:

  1. 重命名方法:

    public dynamic func requestCodeApiGatewayWithPhone(phone: NSString) -> AnyObject
    
  2. 使用手写或shorthand表示法公开外部参数名称:

    public dynamic func requestCodeApiGateway(phone phone: NSString) -> AnyObject
    public dynamic func requestCodeApiGateway(#phone: NSString) -> AnyObject
    
  3. 覆盖在 Objective-C 运行时注册的选择器:

    @objc(requestCodeApiGatewayWithPhone:)
    public dynamic func requestCodeApiGateway(phone: NSString) -> AnyObject
    

选项 1 和 2 将影响任何调用该方法的 Swift 代码,并且所有方法将对 Objective-C 代码和 Objective-C 运行时产生相同的影响。