Swift 3: Protocol Part 3


As I alluded to details about the protocol in two-part (Protocol Part1 and Protocol Part 2) previous posts. Now this my last post with some more information about the protocol. All code example tested on Xcode 8.1.


Class-Only Protocols:

we can stop the protocol adoption to class types by putting class keywords in the protocol inheritance list. This class always should be in first place in the protocols inheritance list, before if the type is going to inherit any other protocol.

protocol ClassOnlyProtocol: class, myProtocol {

}



In this ClassOnlyProtocol can be adopted by class types only if any enum and structure try to write any definition which tries to adopt protocol will end up with a compile-time error.

Protocol Composition

With the help of protocol composition, we can create a single requirement that could combine multiple protocols. It can use a require a type to conform to multiple protocols at once.

protocol FirstName {

    var firstName: String { get }

}

protocol LastName {

    var lastName: String { get }

}

struct Person: FirstName, LastName {

    var firstName: String

    var lastName: String

}


func callingPerson(celebrator: FirstName & LastName) {

    print("Hi Mr. \(celebrator.firstName) \(celebrator.lastName)")

    

}

let birthdayPerson = Person(firstName: "Sanoj", lastName: "Kashyap")

callingPerson(celebrator: birthdayPerson)



Protocol compositions do not define a new, permanent protocol type. Rather, they define a temporary local protocol that has the combined requirements of all protocols in the composition.

How to check Protocol Conformance?


We use “is” and “as” operators to check for conformance of protocol and cast to a specific protocol. Both checking conformance and typecast to protocol type having the same syntax.
“is” operator return true to instance conform the protocol, otherwise false,

let isconform = birthdayPerson is FirstName

print("Person class conforms \(isconform) ") // Person class conform true


let isconform = birthdayPerson is SurName

print("Person class conforms \(isconform) ") // Person class conform false



“as?” downcast the operator and return an optional value of protocol types and this will nil if an instance does not conform to the protocol. 

let isconform = birthdayPerson as? FirstName

print("Person class conforms \(isconform) ") // Person class conform Optional(Person(firstName: "Sanoj", lastName: "Kashyap"))


let isconform = birthdayPerson as? SurName

print("Person class conforms \(isconform) ") // Person class conform nil


“as!” version  of the downcast operator that forces to downcast protocol type and triggers a runtime error if downcast does not succeed

let isconform = birthdayPerson as! FirstName

print("Person class conforms \(isconform) ") Person class conform Person(firstName: "Sanoj", lastName: "Kashyap")


let isconform = birthdayPerson as! SurName

print("Person class conforms \(isconform) ") // Error: Execution was interrupted, reason signal SigaBRT and Print “Could not cast value of type 'Person' (0x1153bf2b8) to 'SurName' (0x115d4d200).”


Now you can see birthdayPerson in let isconform = birthdayPerson as! FirstName, birthdayPerson of type FirstName. so FirstName property will be accessed using birthdayPerson and print in a typesafe way.
Once you typecast the underlying object does not change. As this object is the type of FirstName so it can access "firstName" property.

Optional Protocol Requirements


we can also add an optional requirement for protocol, that requirement does not need to implement by conformance types. The requirement which is optional is a protocol, has to add the “optional” keyword in protocol definitions. The protocol and the optional requirement must be marked with the @objc attribute.

Note:
Note that @objc protocols can be adopted only by classes that inherit from Objective-C classes or other @objc classes. They can’t be adopted by structures or enumerations.
When we use optional property and method in protocol then its type becomes automatically optional.
so for e.g.
a method of type (Int) -> String becomes ((Int) -> String)?. Now the complete function wrapped in the optional, with no means to return a value from a function.

@objc protocol CDataSource {

    @objc optional func somemethod(count: Int) -> Int

    @objc optional var increment: Int { get }

}


Protocol Extensions:

Protocol extension can be used to extend method and property implementations to conforming types.

extension FirstName {

    func addPrefix()  {

    }

}


class MyName: FirstName {

}


let name =  MyName. addPrefix()


Protocol extension to provide a default implementation:

we can use protocol extension to provide a default implementation to any method and computed property requirement of that protocol. If conforming will provide the implementation of protocol requirement then it will override otherwise default one is used.


Wrapping Up: 

So that's all from Protocol's last part. I hope you will get a clear idea about how protocol you can use. So you learned about the protocol. Soon my next topic will on Swift Extension. Please, write to me about if you think to cover any topic in swift.

Enjoying swift 😊






Comments

Popular posts from this blog

Copy Vs Mutable Copy in iOS

How to Disable iOS/iPad App availability on Mac Store, Silicon?

Functions in Swfit 3.0