Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain difference between class and NSObjectProtocol

Tags:

swift

Basically I want to know the difference between this

protocol ViewDelegate: class { 
  func someFunc()
}

and this

protocol ViewDelegate: NSObjectProtocol { 
  func someFunc()
}

Is there any difference ??

like image 927
LeoGalante Avatar asked Apr 03 '17 22:04

LeoGalante


1 Answers

Only Object or Instance type can conform to both type of protocol, where Structure and Enum can't conform to both the type

But the major difference is: If one declares a protocol like below means it is inheriting NSObjectProtocol

protocol ViewDelegate: NSObjectProtocol { 
    func someFunc()
}

if the conforming class is not a child class of NSObject then that class need to have the NSObjectProtocol methods implementation inside it. (Generally, NSObject does conform to NSObjectProtocol)

ex:

class Test1: NSObject, ViewDelegate {
   func someFunc() {
   }
   //no need to have NSObjectProtocol methods here as Test1 is a child class of NSObject
}

class Test2: ViewDelegate {
       func someFunc() {
       }
       //Have to implement NSObjectProtocol methods here
    }

If one declare like below, it means only object type can conform to it by implementing its methods. nothing extra.

protocol ViewDelegate: class { 
  func someFunc()
}
like image 176
Santosh Sahoo Avatar answered Sep 25 '22 13:09

Santosh Sahoo