Protocol Oriented Programming - ios

As we transition our brains from Object Oriented Programming to Protocol Oriented Programming how can I do the following ?
let's say I have a JSON object representing Model has {created_time,updated_time,type,...} and those values are common in 5 Model objects.
is it right to make a protocol contains all the above properties like the following
protocol xxx {
var type : String { get }
var updatedTime : String { get }
var createdTime : String { get }
//...//
}
and then all the 5 structs conform to this protocol

I would say that's a perfectly good solution. The alternative would be having a base class with those properties and have all five of those models inherit from the base class, but there's no particular reason to use inheritance here.
A protocol is just a "contract" that guarantees a class has certain properties or behavior. To me, your example here feels very "contractual."
By contrast, inheritance implies a "is-a" relationship (e.g. a Ford is-a car). To me, this feels more like a contract than an "is-a" case. Of course, neither choice is wrong, but think your protocol idea here is good.

Speaking of Protocol Oriented Programming Swift 2 has protocol extensions which allow default implementations. This also replaces many cases where you would use a superclass instead.
In this case:
// extension of your example protocol
extension xxx {
var type : String { return "a type" }
var updatedTime : String { return "00:00" }
var createdTime : String { return "00:00" }
//...//
}
// struct which conforms to it
struct Astruct: xxx {}
// using the properties
Astruct().type
Astruct().updatedTime
if all properties and methods have a default implementation by the protocol extension you don't have to provide any yourself. However you can "override" them only by implementing them.
So you're decision is right and you should use protocols as often as possible.
The only big drawback is that there is no super where you can explicitly call the default implementations. A workaround (see this answer) would require a superclass which makes the protocol almost redundant.

Related

Get only property defined in protocol causes compilation error when modifying inner property of object

Consider code like this:
protocol SomeProtocol {
var something: Bool { get set }
}
class SomeProtocolImplementation: SomeProtocol {
var something: Bool = false {
didSet {
print("something changed!")
}
}
}
protocol MyProtocol {
var myProperty: SomeProtocol { get }
}
class MyClass: MyProtocol {
var myProperty: SomeProtocol = SomeProtocolImplementation() {
didSet {
print("myProperty has changed")
}
}
}
var o: MyProtocol = MyClass()
o.myProperty.something = true
This code doesn't compile with error:
error: cannot assign to property: 'myProperty' is a get-only property
o.myProperty.something = true
~~~~~~~~~~~~ ^
Why? My property is of type of SomeProtocolImplementation, which is class type so it should be possible to modify it's inner property using reference to myProperty.
Going further, after modifying myProperty definition so that it looks like that:
var myProperty: SomeProtocol { get set }
something weird happens. Now the code compile (not a surprise), but the output is:
something changed!
myProperty has changed
So at this point SomeProtocolImplementation starts behaving like a value type - modyifing it's internal state causes that the "didSet" callback for myProperty is triggered. Just as SomeProtocolImplementation would be struct...
I actually find the solution, but I want also understand what's going on. The solution is to modify SomeProtocol definition to:
protocol SomeProtocol: class {
var something: Bool { get set }
}
It works fine, but I'm trying to understand why it behaves like this. Anybody able to explain?
First read what Class Only Protocol is. Concentrate on the note section that says:
Use a class-only protocol when the behavior defined by that protocol’s requirements assumes or requires that a conforming type has reference semantics rather than value semantics.
Above quote should get you the idea.
You are trying to get the behavior of reference type for your SomeProtocol's conforming class (i.e. SomeProtocolImplementation). You want to be able to change the value of something in future. So basically you are directing to the above quoted sentence.
If you need more clarification please consider the following more meaningful design where I changed the naming for convenience:
protocol Base: class {
var referenceTypeProperty: Bool { get set }
// By now you are assuming: this property should be modifiable from any reference.
// So, instantly make the protocol `Class-only`
}
class BaseImplementation: Base {
var referenceTypeProperty: Bool = false {
didSet {
print("referenceTypeProperty did set")
}
}
}
protocol Child {
var valueTypeProperty: Base { get }
// This property shouldn't be modifiable from anywhere.
// So, you don't need to declare the protocol as Class-only
}
class ChildImplementation: Child {
var valueTypeProperty: Base = BaseImplementation() {
didSet {
print("valueTypeProperty did set")
}
}
}
let object: Child = ChildImplementation()
object.valueTypeProperty.referenceTypeProperty = true
Any class that can provide behavior useful to other classes may declare a programmatic interface for vending that behavior anonymously. Any other class may choose to adopt the protocol and implement one or more of its methods, thereby making use of the behavior. The class that declares a protocol is expected to call the methods in the protocol if they are implemented by the protocol adopter.
Protocol Apple Documentation
When you try to 'set' value to a variable that is read-only - you are trying to change the protocol's implementation. Conforming classes can only consume information from protocol. In Swift we can write protocol extensions where we can have alternative methods for the protocol.
In short think of computed variables as functions. You are technically trying to change a function in this case.
I actually find the solution, but I want also understand what's going on.
I was just about to tell you to make SomeProtocol a class protocol, but you already figured that out. — So I'm a little confused as to what you don't understand.
You understand about reference types and value types, and you understand about class protocols and nonclass protocols.
Well, as long as SomeProtocol might be adopted by a struct (it's a nonclass protocol), then if you are typing something as a SomeProtocol, it is a value type. The runtime isn't going to switch on reference type behavior just because the adopter turns out to be a class instance; all the decisions must be made at compile time. And at compile time, all the compiler knows is that this thing is a SomeProtocol, whose adopter might be a struct.

Hide logic that class conforms to protocol

Are there any ways to hide that class conforms to some protocol? Like in Objective-C - just used to add Protocol in .m file and other classes (from another files) didn't see it.
For example. I have a test cell which has a textfield. I want to hide, that this cell conforms to protocol. Something like that:
class TestCell: UITableViewCell {
}
fileprivate extension TestCell : UITextFieldDelegate {
}
But compiler swears me. Any elegant solution?
This capability has been stated by the Swift team as "unlikely" to be implemented. Here is the original thread about it: https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160229/011666.html
The specific statement about this particular scenario was:
Private conformances
Right now, a protocol conformance can be no less visible than the
minimum of the conforming type’s access and the protocol’s access.
Therefore, a public type conforming to a public protocol must provide
the conformance publicly. One could imagine removing that restriction,
so that one could introduce a private conformance:
public protocol P { }
public struct X { }
extension X : internal P { … } // X conforms to P, but only within this module
The main problem with private conformances is the interaction with
dynamic casting. If I have this code:
func foo(value: Any) {
if let x = value as? P { print(“P”) }
}
foo(X())
Under what circumstances should it print “P”? If foo() is defined
within the same module as the conformance of X to P? If the call is
defined within the same module as the conformance of X to P? Never?
Either of the first two answers requires significant complications in
the dynamic casting infrastructure to take into account the module in
which a particular dynamic cast occurred (the first option) or where
an existential was formed (the second option), while the third answer
breaks the link between the static and dynamic type systems—none of
which is an acceptable result.

Can delegation be implemented in any language or it is language specific

I'm currently trying to understand the delegation pattern and I was wondering if this pattern is language specific, in other words does the language need to have some sort of support for Protocols, Interfaces etc. in order for this pattern to work or it can be implemented in any language?
Swift Example:
protocol SendersMessageDelegate{
func shareMessage(message: String)
}
class Sender{
var sendersMessage: String = String()
var delegate: SendersMessageDelegate?
func sendMessage(sendersMessage: String) {
self.sendersMessage = sendersMessage
delegate?.shareMessage(sendersMessage)
}
}
class Receiver: SendersMessageDelegate{
var savedMessage:String?
func shareMessage(message: String) {
savedMessage = message
print(message)
}
}
var sender = Sender()
var receiver = Receiver()
sender.delegate = receiver
sender.sendMessage("Hello Receiver"
)
Protocols / interfaces allow you to create a clean and generic specification of the interface between the classes involved, but they aren't required. Generally the delegating class knows nothing about the delegate other than that it responds to a set of methods, but again that isn't required - often there are explicit runtime tests to check if it responds to the target methods or not. Strictly speaking it also doesn't need to be classes.
So, any language where you can have multiple code files / 'objects' which refer to another could be described as a delegate relationship. The difference between delegation and composition or simple invocation can be woolly. Abstract interfaces help tip the scale towards delegation.
Any object oriented language can have delegates. It's simply a design pattern that is more widely used and supported in iOS.
Wikipedia's delegation pattern article even has Java examples: https://en.wikipedia.org/wiki/Delegation_pattern

Override var conforming to a protocol with a var conforming to a child of the overridden var protocol

This is my inheritance structure
Protocols
protocol BaseProtocol {
}
protocol ChildProtocol: BaseProtocol {
}
Classes
class BaseClass: NSObject {
var myVar: BaseProtocol!
}
class ChildClass: BaseClass {
override var myVar: ChildProtocol!
}
I'm receiving a compiler error:
Property 'myVar' with type 'ChildProtocol!' cannot override a property with type 'BaseProtocol!'
What is the best approach to achieve this?
UPDATE
I updated the question trying to implement the solution with generics but it does not work :( This is my code (now the real one, without examples)
Protocols
protocol TPLPileInteractorOutput {
}
protocol TPLAddInteractorOutput: TPLPileInteractorOutput {
func errorReceived(error: String)
}
Classes
class TPLPileInteractor<T: TPLPileInteractorOutput>: NSObject, TPLPileInteractorInput {
var output: T!
}
And my children
class TPLAddInteractor<T: TPLAddInteractorOutput>: TPLPileInteractor<TPLPileInteractorOutput>, TPLAddInteractorInput {
}
Well, inside my TPLAddInteractor I can't access self.output, it throws a compiler error, for example
'TPLPileInteractorOutput' does not have a member named 'errorReceived'
Besides that, when I create the instance of TPLAddInteractor
let addInteractor: TPLAddInteractor<TPLAddInteractorOutput> = TPLAddInteractor()
I receive this other error
Generic parameter 'T' cannot be bound to non-#objc protocol type 'TPLAddInteractorOutput'
Any thoughts?
#tskulbru is correct: it can't be done, and this has nothing to do with your protocols. Consider the example below, which also fails…this time with Cannot override with a stored property 'myVar':
class Foo {
}
class Goo: Foo {
}
class BaseClass: NSObject {
var myVar: Foo!
}
class ChildClass: BaseClass {
override var myVar: Foo!
}
To understand why, let's reexamine the docs:
Overriding Properties
You can override an inherited instance or class property to provide
your own custom getter and setter for that property, or to add
property observers to enable the overriding property to observe when
the underlying property value changes.
The implication is that if you are going to override a property, you must write your own getter/setter, or else you must add property observers. Simply replacing one variable type with another is not allowed.
Now for some rampant speculation: why is this the case? Well, consider on the one hand that Swift is intended to be optimized for speed. Having to do runtime type checks in order to determine whether your var is in fact a Foo or a Bar slows things down. Then consider that the language designers likely have a preference for composition over inheritance. If both of these are true, it's not surprising that you cannot override a property's type.
All that said, if you needed to get an equivalent behavior, #tskulbru's solution looks quite elegant, assuming you can get it to compile. :)
I don't think you can do that with protocols
The way i would solve the problem you are having is with the use of generics. This means that you essentially have the classes like this (Updated to a working example).
Protocols
protocol BaseProtocol {
func didSomething()
}
protocol ChildProtocol: BaseProtocol {
func didSomethingElse()
}
Classes
class BaseClass<T: BaseProtocol> {
var myProtocol: T?
func doCallBack() {
myProtocol?.didSomething()
}
}
class ChildClass<T: ChildProtocol> : BaseClass<T> {
override func doCallBack() {
super.doCallBack()
myProtocol?.didSomethingElse()
}
}
Implementation/Example use
class DoesSomethingClass : ChildProtocol {
func doSomething() {
var s = ChildClass<DoesSomethingClass>()
s.myProtocol = self
s.doCallBack()
}
func didSomething() {
println("doSomething()")
}
func didSomethingElse() {
println("doSomethingElse()")
}
}
let foo = DoesSomethingClass()
foo.doSomething()
Remember, you need a class which actually implements the protocol, and its THAT class you actually define as the generic type to the BaseClass/ChildClass. Since the code expects the type to be a type which conforms to the protocol.
There are two ways you can go with your code, depending what you want to achieve with your code (you didn't tell us).
The simple case: you just want to be able to assign an object that confirms to ChildProtocol to myVar.
Solution: don't override myVar. Just use it in ChildClass. You can do this by design of the language Swift. It is one of the basics of object oriented languages.
Second case: you not only want to enable assigning instances of ChildProtocol, you also want to disable to be able to assign instances of BaseProtocol.
If you want to do this, use the Generics solution, provided here in the answers section.
If you are unsure, the simple case is correct for you.
Gerd

How to define an array of objects conforming to a protocol?

Given:
protocol MyProtocol {
typealias T
var abc: T { get }
}
And a class that implements MyProtocol:
class XYZ: MyProtocol {
typealias T = SomeObject
var abc: T { /* Implementation */ }
}
How can I define an array of objects conforming to MyProtocol?
var list = [MyProtocol]()
Gives (together with a ton of SourceKit crashes) the following error:
Protocol 'MyProtocol' can only be used as a generic constraint because it has Self or associated type requirements
Even though the typealias is in fact defined in MyProtocol.
Is there a way to have a list of object conforming to a protocol AND having a generic constraint?
The problem is about using the generics counterpart for protocols, type aliases.
It sounds weird, but if you define a type alias, you cannot use the protocol as a type, which means you cannot declare a variable of that protocol type, a function parameter, etc. And you cannot use it as the generic object of an array.
As the error say, the only usage you can make of it is as a generic constraint (like in class Test<T:ProtocolWithAlias>).
To prove that, just remove the typealias from your protocol (note, this is just to prove, it's not a solution):
protocol MyProtocol {
var abc: Int { get }
}
and modify the rest of your sample code accordingly:
class XYZ: MyProtocol {
var abc: Int { return 32 }
}
var list = [MyProtocol]()
You'll notice that it works.
You are probably more interested in how to solve this problem. I can't think of any elegant solution, just the following 2:
remove the typealias from the protocol and replace T with AnyObject (ugly solution!!)
turn the protocol into a class (but that's not a solution that works in all cases)
but as you may argue, I don't like any of them. The only suggestion I can provide is to rethink of your design and figure out if you can use a different way (i.e. not using typealiased protocol) to achieve the same result.

Resources