21

I'm trying to add a default behavior on some UITextFieldDelegate's methods using protocol extensions like so :

extension ViewController: UITextFieldDelegate {
    // Works if I uncommented this so I know delegates are properly set
//    func textFieldShouldReturn(textField: UITextField) -> Bool {
//        textField.resignFirstResponder()
//        return true
//    }
}

extension UITextFieldDelegate {
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()

        return true
    }
}

As you may guess, the keyboard never dismiss. I can't really see where's the problem here. Is this a language limitation ? Did someone already success doing it ?

EDIT :

As @Logan suggested, default protocol's method implementation doesn't work with protocols marked as @objc. However, UITextFieldDelegate has the following signature public protocol UITextFieldDelegate : NSObjectProtocol {...}

I've test default implementation for NSObjectProtocol and it seems to works fine :

protocol Toto: NSObjectProtocol {
    func randomInt() -> Int
}

extension Toto {
    func randomInt() -> Int {
        return 0
    }
}

class Tata: NSObject, Toto {}

let int = Tata().randomInt() // returns 0

2 Answers 2

9

I can't be 100% positive, but here's what I believe is happening:

Protocol extensions aren't accessible from ObjC. Since UITextFieldDelegate is an ObjC protocol, its reliant on ObjC dispatching. As far as the compiler is concerned, the methods in your default implementation are inaccessible, even though they do exist.

To clarify, we can extend these protocols if its truly an extension and adds behavior. This behavior will only be accessible in Swift and shouldn't be problematic in any way.

The problem is default implementations not being ObjC accessible.

Here's a quick example of a custom version:

@objc protocol Test : class {
    func someFunc() -> String
}

extension Test {
    func someFunc() -> String {
        return ""
    }
}

// Fails here 'candidate is not @objc but protocol requires it`
class Hi : NSObject, Test {

}

Xcode suggests appending @objc but it will keep suggesting this over and over again until you get @objc @objc @objc Hi : ...

Based on our conversation below, I made this which seems to be working. I can't fully explain why yet:

@objc public protocol Toto: UITextFieldDelegate {
    optional func randomInt() -> Int
}

extension Toto {
    func randomInt() -> Int {
        return 0
    }
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        return false
    }
}

class Tata: NSObject, Toto {
}

Ok, I realize that I'm considering a different problem, and while this compiles, it won't work, and the issue is dynamic dispatch. If you try to append your method w/ @objc, or dynamic, the compiler will warn you that you can't dispatch this way, except on classes. Since a protocol exception doesn't conform to this, when ObjC dispatches the message send, it can't find the implementation in your extension.

Since Swift is constantly updating, here's when this answer was applicable:

Swift 2.0 Xcode 7 GM

12
  • UITextFieldDelegate signature looks like public protocol UITextFieldDelegate : NSObjectProtocol {...}. I've just test protocol extension for protocols that implements NSObjectProtocol and it seems to not be problematic. Moreover, shouldn't the compiler warns me if I tried to extend @obj protocols ?
    – Yaman
    Sep 16, 2015 at 14:40
  • @Yaman - We all know that the compiler warnings aren't perfect in Swift, and sometimes its unclear. If you look beyond the does not conform, at least on my system, I also get an @objc warning which keeps adding @objc but never fixes the problem. The issue isn't extending an ObjC protocol, sorry about any confusion. The issue is creating default behavior that is dependent on ObjC accessibility. Extending and adding new methods to an ObjC protocol that are only accessible in Swift is fine. Adding default implementations that must be ObjC accessible is what causes the issue.
    – Logan
    Sep 16, 2015 at 14:43
  • 3
    Okay so if I understand well : protocol extension are purely static dispatch so when UITextFieldDelegate try to call one of his method via objc_msgSend(), it will never reach the default implementation of the protocol extension right ?
    – Yaman
    Sep 16, 2015 at 16:47
  • 1
    That's what I believe is happening, it's the only thing I can think of that makes sense.
    – Logan
    Sep 16, 2015 at 17:56
  • 2
    Yep I think that make sense. Thanks for going to the bottom of this, I'll accept your answer for now but still gonna try to reach Apple for an official response. I'll let to know if I got any news. Cheers.
    – Yaman
    Sep 16, 2015 at 18:28
3

Good discussion here, and exactly what I am suspecting at this point as well. One other thing not mentioned here - perhaps this might be due to a wider issue of obj-c not being able to access the Swift protocol extension implementations.

For example, the following code:

class MyViewController: UIViewController, MyTextFieldDelegateProtocol {
    @IBOutlet weak var textField: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }
}
extension MyViewController: UITextFieldDelegate {
    func textFieldDidBeginEditing(textField: UITextField) {
        print("shouldChangeCharactersInRange called")
    }
}

Will generate the following in the Swift generated header for the extension:

@interface MyViewController (SWIFT_EXTENSION(MyApp)) <UITextFieldDelegate>
- (void)textFieldDidBeginEditing:(UITextField * __nonnull)textField;
@end

However, using protocol extensions as follows (similar to your post):

class MyViewController: UIViewController, MyTextFieldDelegateProtocol {
    // ...
}

@objc protocol MyTextFieldDelegateProtocol: UITextFieldDelegate {}
extension MyTextFieldDelegateProtocol {
    func textFieldDidBeginEditing(textField: UITextField) {
        print("shouldChangeCharactersInRange called")
    }
}

Generates the following in the Swift header for the protocol:

SWIFT_PROTOCOL("_TtP8MyApp27MyTextFieldDelegateProtocol_")
@protocol MyTextFieldDelegateProtocol <UITextFieldDelegate>
@end

The implementation is not visible at all, and so it seems to imply protocol extension implementations are not supported from obj-c. I also found someone asked that question here (although no answers yet): Can Swift Method Defined on Extensions on Protocols Accessed in Objective-c

Unfortunately, I haven't yet found any official apple docs about this limitation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.