Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_cmd in Swift for selector use

I'm trying to write the following ObjC code in Swift 3:

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

But do not know what to replace _cmd with. I'm trying function, but it doesn't work:

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

using #selector(scrollViewDidScroll(_:)) works, but is there a way to keep it generic?

Edit: Possible duplicate answer is about getting function name which isn't what I'm asking above

like image 750
Alexandre G Avatar asked Dec 12 '25 14:12

Alexandre G


1 Answers

Swift doesn't have selectors. Objective-C sends messages to objects while Swift calls functions. So checking if object can respond to selector is part of Objective-C and NSObject.

Swift protocol functions are required by default. Swift compiler doesn't let you skip those function implementations. But you can make them optional, and you have to check, if these functions implemented before calling.

In this case, just call function with question mark at the end, like this

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

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

like image 173
GRiMe2D Avatar answered Dec 15 '25 09:12

GRiMe2D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!