Search Your Question

Some truths about protocol

Q1 : Can structure confirm protocol?
A1 : Yes

Q2 : Can enumeration confirm protocol?
A2 : Yes

Q3 : Can we declare variable in protocol?
A3 : Yes -> It must be var and it must be read-Only or readAndWrite . Property declaration is like following : 

protocol someprotocol {
     var gettable : Int { get }
      var setAndGettable : Int { get set }

Q4 : Can we add function in the enumeration?
A4 : Yes

Q5 : Can protocol has own init method?
A5 : Yes

Q6 : Can protocol inherit another protocol?
A6 : Yes
protocol someprotocol : anotherprotocol {

}

Q7: Can we make a class-specific protocol?
A7: You can limit protocol adoption to class types (and not structures or enumerations) by adding the AnyObject or class protocol to a protocol’s inheritance list.

protocol someprotocol : AnyObject, Someanotherprotocol {
}

Now someprotocol can only be confirmed by class type. No structure or enum type can confirm this protocol.

Q8. Can we declare an optional protocol method in swift?
A8. Yes. In that protocol name and optional methods should be followed by @objc due to it consider as objective c code.

@objc protocol someprotocol {
        @objc optional func somemethod()
        @objc optional var someName : String { get set }
}

or 

We can make protocol extension and provide default body to protocol method. So any class or struct confirms that protocol doesn't require implementing that method.

Q.9 Can protocol be fileprivate?

A9. Yes. Protocol can be fileprivate, private, public. Private and fileprivate protocol can be confirmed only within current file.

Q.10 Can we define property in extension?
A10. Swift doesn’t support stored properties inside the extension. Computed property is allowed in extension.

Q.11 Can we define property in protocol?
A.11 Property in protocol must have explicit { get } or { get set } specifier. 

protocol VoiceAssistant {
        var s : String // Not allowed
        var name: String {get} // Allowed
        var voice: String {get set} // Allowed

    }

Q.12 Can we declare same name property in protocol and its extension with different datatype?
A.12 Yes. Extension declared property must have valid getter method.

protocol VoiceAssistant {
   
    var name: String {get}
    var voice: String {get set}
}

extension VoiceAssistant {
    var name: Int {get { return 5}}

}

Q.13 Can we define body in method in protocol? How?
A.13 Yes.

protocol VoiceAssistant {
    func makeMessage()
}

extension VoiceAssistant {
    func makeMessage() {
        print("Default make message method")
    }

}


1 comment:

  1. Thanks for this blog. I have also prepared top listed IOS Interview Questions for beginners. Please look into it.And share your feedback by replying my comment.

    ReplyDelete

Thanks