Swift 中的 _cmd 供选择器使用

_cmd in Swift for selector use

我正在尝试在 Swift 3 中编写以下 ObjC 代码:

- (void)scrollViewScroll:(UIScrollView*)scrollView {
    // some code
    if ([_userDelegate respondsToSelector:_cmd]) {
        [_userDelegate scrollViewDidEndDecelerating:scrollView];
    }
}

但是不知道用什么来代替_cmd。我正在尝试功能,但它不起作用:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    // some code
    if (userDelegate?.responds(to: #function))! {
        userDelegate?.scrollViewDidScroll!(scrollView)
    }
}

使用 #selector(scrollViewDidScroll(_:)) 可行,但有没有办法让它保持通用?

编辑: 可能重复的答案是关于获取函数名称,这不是我上面要问的

Swift 没有选择器。 Objective-C 向对象发送消息,而 Swift 调用函数。因此,检查对象是否可以响应选择器是 Objective-C 和 NSObject.

的一部分

Swift协议函数默认为required。 Swift 编译器不允许您跳过这些函数实现。但是你可以让它们optional,你必须检查,如果这些函数在调用之前实现了。

在这种情况下,就调用最后带问号的函数,像这样

if let returnValue = userDelegate?.theOptionalFunction?(arguments) {
    // you got value
} else {
    // delegate returned nil or delegate function isn't implemented
}

来源:The Swift Programming Language

An optional protocol requirement can be called with optional chaining, to account for the possibility that the requirement was not implemented by a type that conforms to the protocol. You check for an implementation of an optional method by writing a question mark after the name of the method when it is called, such as someOptionalMethod?(someArgument).