I have a swift protocol:
#objc protocol SomeDelegate {
optional func myFunction()
}
I one of my classes I did:
weak var delegate: SomeDelegate?
Now I want to check if the delegate has myFunction implemented.
In objective-c I can do:
if ([delegate respondsToSelector:#selector(myFunction)]) {
...
}
But this is not available in Swift.
Edit: This is different from: What is the swift equivalent of respondsToSelector? I focus on class protocols not on classes.
How do I check if my delegate has an optional method implemented?
Per The Swift Programming Language:
You check for an implementation of an optional requirement by writing
a question mark after the name of the requirement when it is called,
such as someOptionalMethod?(someArgument). Optional property
requirements, and optional method requirements that return a value,
will always return an optional value of the appropriate type when they
are accessed or called, to reflect the fact that the optional
requirement may not have been implemented.
So the intention is not that you check whether the method is implemented, it's that you attempt to call it regardless and get an optional back.
You can do
if delegate?.myFunction != nil {
}
I've found it successful to add an extension to the protocol that defines basic default implementation and then any class implementing the protocol need only override the functions of interest.
public protocol PresenterDelegate : class {
func presenterDidRefreshCompleteLayout(presenter: Presenter)
func presenterShouldDoSomething(presenter: Presenter) -> Bool
}
then extend
extension PresenterDelegate {
public func presenterDidRefreshCompleteLayout(presenter: Presenter) {}
public func presenterShouldDoSomething(presenter: Presenter) -> Bool {
return true
}
}
Now any class needing to conform to the PresenterDelegate protocol has all functions already implemented, so it's now optional to override it's functionality.
I normally implement it like this:
self.delegate?.myFunction?()
if the delegate methods returns a value:
var result = defaultValue
if let delegateResult = self.delegate?.myFunction?() else {
result = delegateResult
}
//do something with result
Declaration
#objc public protocol nameOfDelegate: class {
#objc optional func delegateMethod(_ varA: int, didSelect item: Item)
}
Implimetation
if let delegate = nameOfDelegate {
delegate.delegateMethod?(1, didDeselect: node)
}
I know this question is 5 years old, but I would like to share what I found. My solution works as of 2021, XCode 11+, Swift 5.
Say I wanted to figure out whether the function sign follows the GIDSignInDelegate protocol and also know what all the optional functions for GIDSignInDelegate are.
I have to look at the source code of the GIDSignIn module, and this is how.
Click on jump to definition on the main module that is imported. It will lead to a file like this:
Copy the entire line, import GoogleSignIn.GIDSignIn and paste it in the ViewController or whatever .swift file (doesn't really matter).
Within the swift file, right click on the GIDSignIn part of the import line GoogleSignIn.GIDSignIn and jump to definition. This will lead you to the actual module with all the available functions (the functions not marked optional may be stubs, which are required functions in the delegate protocol):
From this file, I can see that there is a sign function that is a stub of GIDSignInDelegate and an optional sign function that is implemented as a method overload.
I used this for GIDSignInDelegate, but you can use the same method to figure out whether any function follows any delegate protocol.
Related
I have a very general view that is created and used by multiple view controllers with 2 buttons, one of them sometimes is hidden depending on the needs.
This view delegates the tap of the two buttons.
protocol TheViewsDelegate: class {
func button1Tapped()
func button2Tapped()
}
Let's put that ViewControllerA creates this view and needs both buttons, this view controller will have to implement both delegate functions and do something inside it.
Now let's say that ViewControllerB creates the same view but just needs one of the buttons. This view controller will have to still implement button2Tapped() even though it will never be called and used.
Is there a way to handle this nicely? I imagine there's a nice solution where I don't need to implement this button2Tapped() if I don't need it.
I thought about making it optional by giving a default implementation but I don't like this solution, I like (and I think it's a good practice) the compiler giving me an error when a method it's not implement. Someone can jump into the project and not realising that he/she hasn't implement button2Tapped when needs to be implemented.
Note: This is a very simple example just to illustrate my question, but the question is more broad as in what to do when a function in a delegate is defined by controller that don't need to implement it.
I believe you want to use:
optional func
There are a couple of ways of declaring a protocol method as optional, one is using optional func which requires using #objc syntax, which a lot of programmers apparently don't like, and the other requires declaring an empty body in the extension of a protocol (which makes it optional by default).
protocol TheViewsDelegate: AnyObject {
func button1Tapped()
}
extension TheViewsDelegate {
func button2Tapped() {}
}
class SomeViewController: UIViewController, TheViewsDelegate {
func button1Tapped() {
// implement
}
}
By giving the protocol an empty body inside an extension of the protocol, that method is optional and does not need to be implemented by conforming objects.
For comparison, the alternative:
#objc protocol TheViewsDelegate: AnyObject {
func button1Tapped()
#objc optional func button2Tapped()
}
class SomeViewController: UIViewController, TheViewsDelegate {
func button1Tapped() {
// implement
}
}
Is there a way to set extensions during run time in Swift?
I got a protocol named "CuteProtocol" and an extension to that protocol named "CuteExtension". When I want to add this extension to classes I just do as follows:
class CuteClass: UIViewController, CuteProtocol {
}
However I have many of these classes which should implement this protocol and I don't want to add them one by one, I don't want to make a base class either.
Is there a way to set extensions-protocols during run time as follows:
let cuteClass = CuteClass()
cuteClass. // ADD EXTENSION-PROTOCOL SOMEHOW HERE.
No, but you can extension for example UIViewController, or other base class
extension UIViewController: CuteProtocol {
// your code conforming to Cute Protocol goes here.
}
you can play with runtime modifiers in ObjC freely, but in Swift such kinda pattern is not really common.
NOTE: you can find more information about this in the ObjC Runtime Library, if you are interested.
You can not set extensions in runtime, BUT you don't have to set them in class definition either. you can extend classes like:
extension CuteClass: CuteProtocol {
// your code conforming to Cute Protocol goes here.
}
Update 1
Or if you want to have default implementations to CuteProtocol, you can extend CuteProtocol itself too:
protocol CuteProtocol {
func f1()
}
extension CuteProtocol {
func f1() {
// default implementation
}
}
This way each class can change f1 implementation if want to or use the default implementation.
You can even add conditional extensions like:
extension CuteProtocol where Self: CuteClass {
func f1() { }
func f2() { }
}
so if you write extension CuteClass: CuteProtocol {} all CuteClass instances and subclasses will have access to method f1 and f2.
But be-aware that functions added in extensions support dynamic-dispatch IFF they're defined in protocol.
In the sample I provided, f1 will be called with dynamic-dispatch but f2 will be called with static-dispatch. i.e: if CuteChildClass: CuteClass changes f2 implementation and you call f2 from a CuteProtocol variable, the code you provided in the extension will be called.
TL;DR
How can I define optional methods in a swift protocol that accept custom typed parameters?
The case
I understand that the way to define optional methods in a swift protocol is using the #objc flag. Like so:
#objc protocol someSweetProtocol {
optional func doSomethingCool()
}
But when I wanted to use my custom type for the parameter, like so:
#objc protocol someSweetProtocol {
optional func doSomethingCool(🚶🏼: HSCoolPerson)
}
I got this error:
Which is not cool.
How can this problem be solved? Also can you explain why this is happening?
Addendum
This is how HSCoolPerson is defined:
class HSCoolPerson {
...
...
...
}
Nothing special there...
The problem is this:
class HSCoolPerson {
// ...
}
As the error message plainly tells you, that type, the class HSCoolPerson, is completely invisible to Objective-C. And a protocol optional method is an Objective-C language feature; Swift merely borrows it, as it were. (That's why you have to say #objc protocol to get this feature.) So any time you want to define a protocol optional method, you have to do it in a way that Objective-C can understand, because it is Objective-C that is going to do the work for you.
To expose this class to Objective-C, simply derive it from NSObject:
class HSCoolPerson : NSObject {
// ...
}
Problem solved.
Put the default implementations in an extension, like so:
class HSCoolPerson {}
protocol SomeSweetProtocol {
func doSomethingCool()
}
extension SomeSweetProtocol {
func doSomethingCool(🚶🏼: HSCoolPerson) {
// default implementation here
}
}
class SomeSweetClass: SomeSweetProtocol {
// no implementation of doSomethingCool(_:) here, and no errors
}
you can declare func like that in protocol
#objc optional func doSomethingCool(🚶🏼: HSCoolPerson)
This is my inheritance structure
Protocols
protocol BaseProtocol {
}
protocol ChildProtocol: BaseProtocol {
}
Classes
class BaseClass: NSObject {
var myVar: BaseProtocol!
}
class ChildClass: BaseClass {
override var myVar: ChildProtocol!
}
I'm receiving a compiler error:
Property 'myVar' with type 'ChildProtocol!' cannot override a property with type 'BaseProtocol!'
What is the best approach to achieve this?
UPDATE
I updated the question trying to implement the solution with generics but it does not work :( This is my code (now the real one, without examples)
Protocols
protocol TPLPileInteractorOutput {
}
protocol TPLAddInteractorOutput: TPLPileInteractorOutput {
func errorReceived(error: String)
}
Classes
class TPLPileInteractor<T: TPLPileInteractorOutput>: NSObject, TPLPileInteractorInput {
var output: T!
}
And my children
class TPLAddInteractor<T: TPLAddInteractorOutput>: TPLPileInteractor<TPLPileInteractorOutput>, TPLAddInteractorInput {
}
Well, inside my TPLAddInteractor I can't access self.output, it throws a compiler error, for example
'TPLPileInteractorOutput' does not have a member named 'errorReceived'
Besides that, when I create the instance of TPLAddInteractor
let addInteractor: TPLAddInteractor<TPLAddInteractorOutput> = TPLAddInteractor()
I receive this other error
Generic parameter 'T' cannot be bound to non-#objc protocol type 'TPLAddInteractorOutput'
Any thoughts?
#tskulbru is correct: it can't be done, and this has nothing to do with your protocols. Consider the example below, which also fails…this time with Cannot override with a stored property 'myVar':
class Foo {
}
class Goo: Foo {
}
class BaseClass: NSObject {
var myVar: Foo!
}
class ChildClass: BaseClass {
override var myVar: Foo!
}
To understand why, let's reexamine the docs:
Overriding Properties
You can override an inherited instance or class property to provide
your own custom getter and setter for that property, or to add
property observers to enable the overriding property to observe when
the underlying property value changes.
The implication is that if you are going to override a property, you must write your own getter/setter, or else you must add property observers. Simply replacing one variable type with another is not allowed.
Now for some rampant speculation: why is this the case? Well, consider on the one hand that Swift is intended to be optimized for speed. Having to do runtime type checks in order to determine whether your var is in fact a Foo or a Bar slows things down. Then consider that the language designers likely have a preference for composition over inheritance. If both of these are true, it's not surprising that you cannot override a property's type.
All that said, if you needed to get an equivalent behavior, #tskulbru's solution looks quite elegant, assuming you can get it to compile. :)
I don't think you can do that with protocols
The way i would solve the problem you are having is with the use of generics. This means that you essentially have the classes like this (Updated to a working example).
Protocols
protocol BaseProtocol {
func didSomething()
}
protocol ChildProtocol: BaseProtocol {
func didSomethingElse()
}
Classes
class BaseClass<T: BaseProtocol> {
var myProtocol: T?
func doCallBack() {
myProtocol?.didSomething()
}
}
class ChildClass<T: ChildProtocol> : BaseClass<T> {
override func doCallBack() {
super.doCallBack()
myProtocol?.didSomethingElse()
}
}
Implementation/Example use
class DoesSomethingClass : ChildProtocol {
func doSomething() {
var s = ChildClass<DoesSomethingClass>()
s.myProtocol = self
s.doCallBack()
}
func didSomething() {
println("doSomething()")
}
func didSomethingElse() {
println("doSomethingElse()")
}
}
let foo = DoesSomethingClass()
foo.doSomething()
Remember, you need a class which actually implements the protocol, and its THAT class you actually define as the generic type to the BaseClass/ChildClass. Since the code expects the type to be a type which conforms to the protocol.
There are two ways you can go with your code, depending what you want to achieve with your code (you didn't tell us).
The simple case: you just want to be able to assign an object that confirms to ChildProtocol to myVar.
Solution: don't override myVar. Just use it in ChildClass. You can do this by design of the language Swift. It is one of the basics of object oriented languages.
Second case: you not only want to enable assigning instances of ChildProtocol, you also want to disable to be able to assign instances of BaseProtocol.
If you want to do this, use the Generics solution, provided here in the answers section.
If you are unsure, the simple case is correct for you.
Gerd
Exploring Swift headers I'm seeing this pattern used by Apple, in particular the init declaration of the following struct HAS NO IMPLEMENTATION.
Obviously the init() implementation is hidden somehow, since it's Apple stuff, but I was trying to understand how.
This is only an example, but it seems a common behavior in the headers
struct AutoreleasingUnsafePointer<T> : Equatable, LogicValue {
let value: Builtin.RawPointer
init(_ value: Builtin.RawPointer) // <---- how is it possible? where is the implementation?
func getLogicValue() -> Bool
/// Access the underlying raw memory, getting and
/// setting values.
var memory: T
}
I know that it is possible to declare a protocol plus a class extension, doing this it's possible to "hide" the implementation from the class declaration and moving it elsewhere
class TestClass :TestClassProtocol
{
// nothing here
}
protocol TestClassProtocol
{
func someMethod() // here is the method declaration
}
extension TestClass
{
func someMethod() // here is the method implementation
{
println("extended method")
}
}
But it's different from what I have seen in the Apple Headers, since the method "declaration" is inside the "class", not inside the "protocol". if I try to put the method declaration inside the class TestClass, however, I have two errors (function without body on the class, and invalid redeclaration on the extension)
In Objective C this was "implicit", since the method declaration was in the .h and the implementation in the .m
How to do the same in Swift?
I think the explanation is very simple. What you see in Xcode is not actually a valid Swift
code.
It's a result from an automatic conversion of an Obj-C header into Swift-like code but it's not compilable Swift.