Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2, protocol extensions & respondsToSelector

I am not sure, it looks to me that it is some kind of bug or bad implementation with protocol extensions in Swift 2.0.

I have protocolA, protocolB extending protocolA and implementing methods in protocolB extension.

I have conformed an class instance to conform to protocolB, however when inspected by respondsToSelector for protocolA/B methods the results is false.

import Cocoa
import XCPlayground

protocol ProtocolA : NSObjectProtocol {
  func functionA()
}

protocol ProtocolB : ProtocolA {
  func functionB()
}

extension ProtocolB {
   func functionA() {
     print("Passed functionA")
   }

   func functionB() {
     print("Passed functionB")
   }
}

class TestClass : NSObject, ProtocolB {

    override init () {

    }
}

var instance:TestClass = TestClass()
instance.functionA() // Calls code OK..

if instance.respondsToSelector("functionA") {
    print("Responds to functionA") // **False, never passing here**
}

if instance.respondsToSelector("functionB") {
    print("Responds to functionB") // **False, never passing here**
}

Should be reported as a bug?

like image 683
Jan Kubny Avatar asked Jun 25 '15 20:06

Jan Kubny


People also ask

Can you extend protocols Swift?

In Swift, you can even extend a protocol to provide implementations of its requirements or add additional functionality that conforming types can take advantage of. For more details, see Protocol Extensions. Extensions can add new functionality to a type, but they can't override existing functionality.

What is protocol extension in Swift?

Protocols let you describe what methods something should have, but don't provide the code inside. Extensions let you provide the code inside your methods, but only affect one data type – you can't add the method to lots of types at the same time.

Can Swift override extension?

Swift extensions can add new capabilities to a type, but they cannot override anything. You can add completely new functionality with a very similar name to a method, but it cannot be the same and must be unique, and cannot use the override keyword.

Can Swift create private extensions?

In Swift 4, an extension can reach across to a private declaration. This only applies to extensions that live in the same source file as the private declaration. In other words, an entity that is declared private is accessible from within any extensions for that type within the same source file.


1 Answers

Interesting. Looks like a bug to me. It does recognize functions on a class, but not on extension. No matter what type Instance has. Moreover without an extension code would not be compilable, since protocol methods are non optional. So really looks like a bug/feature? in responds to selector implementation.

like image 171
Nikita Leonov Avatar answered Sep 26 '22 04:09

Nikita Leonov