Objective c calling optional protocol method

Posted: ADFluke Date: 22.06.2017
objective c calling optional protocol method

Swift optional protocols - right now, they don't exist unless the protocol is tagged with objc. So far, this has been an acceptable solution for providing optional method functionality. I will argue that this is a poor way to think about optional protocol swift methods.

This particular solution is a relic of an dynamic language approach that we are familiar with as Objective-C developers. Swift code should take another approach. Protocols serve a lot of different purposes, more so in Swift than in Objective-C. When a design calls for an optional method, it is typically for two reasons that are best exemplified by the delegate design pattern:.

objective c - Why do unimplemented optional protocol methods cause runtime errors when that method is called in obj-c? - Stack Overflow

These are necessary operations, even in Swift. The implementation of optionality, however, should respect the features of the language. An optional method is another way of saying "a method with default behavior. Required methods on the other hand, do not have default behavior: Optional protocol methods are a relatively recent addition to Objective-C. Prior to ObjC 2.

iPhone Development Objective-C: Protocols

Objects that wished to take advantage of delegate methods would override the NSObject implementation. The drawback here was that one couldn't have required methods checked at compile-time; the method was always implemented by every object!

Protocol

The workaround was having the default implementation fail in some way, requiring implementors to override the method to prevent the failure. That was a bummer: In Swift, there is also no way to mark a protocol method as optional. One could probably argue that this is the necessary behavior of statically typed languages, but I won't pretend to have considered every use case. Applying objc to protocols to get method optionality isn't the solution, though - marking a protocol as objc strips some of the Swift-power from a protocol.

Instead, we can borrow a page from old school Objective-C and improve upon it: While similar to Objective-C informal protocols, this is better for two reasons: Now, the astute reader may be wondering about handling the case where the delegate is nil. In Objective-C, with protocols, we often did something that was actually rather unsafe: For example, methods like -objectShouldDoMoreWork: If the default were YES, we'd just change the method name to -objectShouldDoLessWork: I sometimes wonder if the power of Objective-C was C-abusing serendipity or stuff like this was planned.

Swift doesn't care much for serendipity. Let's build the same protocol in Swift. This isn't desirable - in order to get the default behavior, the delegating object must duplicate the default behavior at the call site and in the extension. This is a bug waiting to happen. However, we can solve this problem by having the delegating object implement the delegate protocol in tvb stock market drama extension.

It's a short line, and it is weird, but consider this: Conceptually, this is no different than the Objective-C protocol approach. I'd argue this Swift approach is even cleaner. This allows us to change the call site in Swift to default back to its own implementation in the objective c calling optional protocol method of not having a delegate:. The default behavior is now described just once, and no extra types or objects have been created. More importantly, the world outside of the DelegatingObject is consistent: Contrast this to a solution where the delegate property is set to self or some default object; an external observer would see that the delegate property as populated.

Again, to the astute reader, there is still a problem here: While rare, this is something that happens - UITableViewDataSource is an example. In the case of this extension approach, mixing in required methods causes an issue.

If the extension implements a method, it is technically no longer required - there is a default implementation and implementors can omit it.

objective c calling optional protocol method

If the extension omits the implementation, then we have to implement those required methods in the delegating object - which doesn't make sense and it's a bunch of extra code that'll never get executed. To solve this issue, we can split the required and optional methods.

Required methods go in one protocol, optional go another. The good news is that the default implemented optional methods can be added to the required protocol:. Another approach is to use protocol composition for the required and optional protocols to form a full protocol, instead of having AProtocol inherit from AProtocolOptional.

Now, the extension stuff only deals with the optional part of the full protocol. There is one oddly unnecessary typecast to use, but using AProtocol looks like this:. If you don't like the typecast, you can move that bit of code into a private, computed property which can correctly infer the type without a cast:.

It may be unlikely in Swift. We had an internal discussion on why this was the case. It could technically be possible by allowing implementations within the protocol declaration, which would be syntactic sugar for an extension. The compiler would have to relax the restriction on extensions to allow for partially implemented protocol extensions.

If the compiler is enforcing that protocol conformers have all methods implemented, it should be able to check if all methods are implemented by joining the class and protocol extension.

objective c calling optional protocol method

A protocol could then be partially extended, because the rest of the program guarantees the protocol to be implemented by virtue of all conformers being checked for full implementation. We're not sure if this is possible. Click here for an article about blocks and delegates, another instance where you should use delegation! For the past 16 years, Joe Conway has programmed everything from macOS to Android to iOS.

As a former instructor and lead developer at Big Nerd Ranch, he fine-tuned his skills and expertise in overall mobile strategy, specializing in iOS Development. Author of "iOS Programming: The Big Nerd Ranch Guide," an Amazon Best-Seller, Joe quickly made a name for himself in the mobile space.

He has worked with Fortune companies, technology start-ups and government entities to build mobile platforms, enhance existing applications and develop mobile strategies. Joe was recently named one of Atlanta Business Chronicle's "People on the Move.

Blog How Do I Implement Optional Delegate Protocol Methods In Swift Without objc? How Do I Implement Optional Delegate Protocol Methods In Swift Without objc? When a design calls for an optional method, it is typically for two reasons that are best exemplified by the delegate design pattern: Get something from the delegating objectlike a value or an notification of an event.

For example, this is how UIImagePickerController delivers its image and how UITextField notifies its delegate of changed text. These could be generalized as 'callback' protocol methods. Provide information back to the delegating object; either to dictate behavior or to provide dynamic values for some operation.

UITableView 's dataSource does this to provide row content and UITextFields uses this idea to filter keyboard input. These types of methods could be generalized as 'provider' protocol methods. The Objective-C approach to implementing default behavior happens at the call site: This allows us to change the call site in Swift to default back to its own implementation in the event of not having a delegate: The good news is that the default implemented optional methods can be added to the required protocol: There is one oddly unnecessary typecast to use, but using AProtocol looks like this: About The Author For the past 16 years, Joe Conway has programmed everything from macOS to Android to iOS.

Where to find us Twitter. Home Work Services Blog About Contact Jobs. Subscribe to our Blog.

Rating 4,9 stars - 471 reviews
inserted by FC2 system