gpt4 book ai didi

objective-c - Swift 中的 _cmd 供选择器使用

转载 作者:搜寻专家 更新时间:2023-11-01 07:17:49 25 4
gpt4 key购买 nike

我正在尝试在 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 协议(protocol)函数是必需的。 Swift 编译器不会让你跳过那些函数实现。但是您可以将它们设为可选,并且您必须在调用之前检查这些函数是否已实现。

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

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).

关于objective-c - Swift 中的 _cmd 供选择器使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41053483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com