iOS: MVVM-C ViewController super class - ios

I have MVVM-C arch. Each UIViewController has a ViewModel and CoordinatorDelegate to notify the Coordinator when navigation needs to be performed. The code that create the VC repeat itself, and I though it would be great to create a super class to unify all static funcs that create the VC. Like this:
import UIKit
class MVVMCViewController: UIViewController {
weak var coordinatorDelegate: CoordinatorDelegate?
var viewModel: Modelling?
static func initVC(storyboard: Storyboard,
coordinatorDelegate: CoordinatorDelegate?,
viewModel: Modelling?) -> Self {
let viewController = Self.instantiate(in: storyboard)
viewController.coordinatorDelegate = coordinatorDelegate
viewController.viewModel = viewModel
return viewController
}
}
All CoordinatorDelegateProtocols will inherit from CoordinatorDelegate and all ViewModels will be inheriting from Modelling
But the subclassing does not work smoothly.
Any ideas?

Hi this model wouldn't work fine.
MVVMCViewController has hardcoded protocols as variable type, so You should have the same in your childVC.
To make it work as u want MVVMCViewController show be generic (but can be a lot of issues with it), like
class MVVMCViewController<T: Modelling, U: CoordinatorDelegate>: UIViewController {
weak var coordinatorDelegate: U?
var viewModel: T?
}
or add just casted properties to ConnectViewController
class ConnectViewController: MVVMCViewController {
weak var coordinatorDelegate: CoordinatorDelegate?
var viewModel: Modelling?
var currentDelegate: ConnectViewControllerCoordinatorDelegate? {
coordinatorDelegate as? ConnectViewControllerCoordinatorDelegate
}
var currentVM: ConnectViewModel? {
viewModel as? ConnectViewModel
}
}

Your superclass MVVMCViewController defines two properties coordinatorDelegate and viewModel. If you just need to access them in your child class ConnectViewController, just access it normally. You don't need to define it again.
Also, in your parent class, you have weak var coordinatorDelegate: CoordinatorDelegate?. But in your child class (ConnectViewController), you redeclare the property with a different type (ConnectViewControllerCoordinatorDelegate?). That is illegal, even if it is a subclass of CoordinatorDelegate.
Hence, either
Rename the property in child class to avoid the conflict
Keep the name and the type, but add an override keyword for the property if you plan to add additional functionality in your child class
Do not declare the property again at all in your child class if you don't need to add additional functionality to it. Just access it directly.
Refer to how inheritance works in Swift over here: https://docs.swift.org/swift-book/LanguageGuide/Inheritance.html

Related

Overriding variable property with different type

I have a variable 'children', which is just a list of participants. Can one please explain how can I override a variable with one type to a property with another type.
Here is a code:
class ParticipantsListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var participantsTableView: UITableView!
// Error on next line: Property 'children' with type '[Child]?' cannot override a property with type '[UIViewController]'
var children: [Child]?
var trackingHelper = TrackingHelper()
var modelHelper = ModelHelper.shared
}
The problem is very simple. You can't do that. UIViewController, the class you're inheriting from, has this property under lock and key. You'll need to create yourself a new solution depending on what you're trying to achieve:
Condition A: Child is a subclass of UIViewController
In this case, you want a way to make the child view controllers of ParticipantsListViewController always conform to Child. One way to do this would be the following computed property:
var listChildren: [Child] {
return children.filter { $0 is Child }
}
Condition B: Child is NOT a subclass of UIViewController
You're trying to override something that the system needs to be there. Things in the children array have to be instances or subclasses of UIViewController. It's strict.
Your solution here is easy. Name the property differently and get rid of the override. Sure, it won't have the nicest, simplest name children, but that's the way it goes.
No, you can't have children property with your custom type since property with the same name is already property of UIViewController (see docs) which is superclass of your view controller so your subclass has this property too.
So, you have to use other name for your variable.
You can accomplish this using protocol conformance for your Child view controllers as demonstrated here:
import UIKit
protocol ChildProtocol { }
class SomeViewController: UIViewController, ChildProtocol { }
class ParticipantsListViewController: UIViewController {
override var children: [UIViewController] {
return self.children.filter { viewController in viewController is ChildProtocol }
}
}
So long as the view controllers that you wish to be a Child conform to ChildProtocol, then they will be returned via the children override.

Cant typecast variable to specific child class involving Generics

Note: Sorry could not come-up with better title than this, so please
suggest a better one if you come across one after reading the question
I have a BasePresenter class, That should take BaseInteractor and BaseRouter as its init arguments, and each child class of BasePresenter should be able to specify subclass of BaseInteractor and BaseRouter in their implementation
So I have declared my BasePresenter as
open class PRBasePresenter<T: PRBaseInteractor, R: PRBaseRouter> {
var interactor: T!
var router: R!
let disposeBag = DisposeBag()
convenience init(with router : R, interactor : T) {
self.init()
self.router = router
self.interactor = interactor
}
}
So now PRBaseCollectionsPresenter which is a child of PRBasePresenter declares its interactor and router as
class PRBaseCollectionsPresenter: PRBasePresenter<PRBaseCollectionsInteractor, PRBaseCollectionRouter> {
//other code here
}
Obviously PRBaseCollectionsInteractor is a subclass of PRBaseInteractor and PRBaseCollectionRouter is a subclass of PRBaseRouter
Everything works till here fine. Now comes the issue. Every ViewController should have presenter as a property. So I have a protocol which mandates that with
protocol PresenterInjectorProtocol {
var presenter : PRBasePresenter<PRBaseInteractor, PRBaseRouter>! { get set }
}
And my BaseViewController confirms to PresenterInjectorProtocol
public class PRBaseViewController: UIViewController,PresenterInjectorProtocol {
var presenter: PRBasePresenter<PRBaseInteractor, PRBaseRouter>!
//other code...
}
Now lets say I have ChildViewController, it will obviously get presenter because of inheritance, but obviously child would want to have its specific presenter than having a generic one. And obviously in Swift when you override a property you cant change the type of the variable. So the only way is
class PRBaseTableViewController: PRBaseViewController {
var tableSpecificPresenter: PRBaseCollectionsPresenter {
get {
return self.presenter as! PRBaseCollectionsPresenter
}
}
//other code goes here
}
This gives me a warning
Cast from 'PRBasePresenter!' to
unrelated type 'PRBaseCollectionsPresenter' always fails
And trying to ignore it and running will result in crash :(
How can I solve this problem? What am I doing wrong? Or is this approach completely wrong?

Swift - Initializing model object with properties across multiple views

A client wants me to initialize a model object, but the issue I'm facing is that the properties I need are located across five view controllers. At view controller 1 I define propertyA for my object. View controller 2 I define propertyB, and so on. On the final view I get to see a summary of what i've chosen and from there I can finally create my object.
I'm doing this incredibly long and inefficient at the moment where I have the same optional variables for each property across many views. Any help would be great.
For this scenario you should try Singleton pattern
Create class having all properties and create its singleton also:
public class Property {
public var propertyA:AnyObject? /// define your appropriate data type
public var propertyB:AnyObject?
public var propertyC:AnyObject?
public var propertyD:AnyObject?
public var propertyE:AnyObject?
static let sharedInstance = Property()
}
To Set Values in different-2 view controller follow below pattern. Here I am assuming that you can set property any place in view controller. For now I am considering to viewDidLoad you can change value to any part of view controller
class ViewController1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Property.sharedInstance.propertyA = "X" as AnyObject //// Value should be of same data type of propertyA
}
}
class ViewController2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Property.sharedInstance.propertyB = "Y" as AnyObject //// Value should be of same data type of propertyA
}
}
etc
finally at the end you will get values of all assigned parameters
print(Property.sharedInstance.propertyA)
print(Property.sharedInstance.propertyB)
print(Property.sharedInstance.propertyC)
print(Property.sharedInstance.propertyD)
print(Property.sharedInstance.propertyE)

Having a property which can be any object that adheres to a specific protocol

I'm building an app in Swift, and I have a a view controller which I am going to use in 2 places to display very similar screens but with some minor differences.
I have a protocol called myProtocol, and I've a view controller with a property called viewModel which adheres to this protocol. The viewModel can be an instance of aViewModel or bViewModel, but they both have the same methods from the protocol, but return different values depending on where the view controller is used.
Now, in objective-c I can do
#property (nonatomic, strong) id <myProtocol>viewModel
and then can set it as viewModel = [aViewmodel new] or viewModel = [bViewmodel new]. How can I achieve something similar in swift?
I've tried adding the property as let viewModel: myProtocol? = nil, but this is giving an error saying it can't infer a type. Just wondinerg if you guys could give me some advice. I'm new enough to swift, but have been using Objective-c for a few years
Assuming you are using Swift 3:
protocol MyProtocol {
//...
}
var viewModel:MyProtocol?
class ViewModel: MyProtocol {
//...
}
viewModel = ViewModel()

Swift Property that conforms to a Protocol and Class

#property (strong, nonatomic) UIViewController<UITableViewDelegate> *thing;
I want to implement a property like in this Objective-C code in Swift. So here is what I've tried:
class AClass<T: UIViewController where T: UITableViewDelegate>: UIViewController {
var thing: T!
}
This compiles. My problem comes when I add properties from the storyboard. The #IBOutlet tag generates an compiler error.
class AClass<T: UIViewController where T: UITableViewDelegate>: UIViewController {
#IBOutlet weak var anotherThing: UILabel! // error
var thing: T!
}
The error:
Variable in a generic class cannot be represented in Objective-C
Am I implementing this right? What can I do to fix or get around this error?
EDIT:
Swift 4 finally has a solution for this problem. See my updated answer.
Update for Swift 4
Swift 4 has added support for representing a type as a class that conforms to a protocol. The syntax is Class & Protocol. Here is some example code using this concept from "What's New in Swift" (session 402 from WWDC 2017):
protocol Shakeable {
func shake()
}
extension UIButton: Shakeable { /* ... */ }
extension UISlider: Shakeable { /* ... */ }
// Example function to generically shake some control elements
func shakeEm(controls: [UIControl & Shakeable]) {
for control in controls where control.isEnabled {
control.shake()
}
}
As of Swift 3, this method causes problems because you can't pass in the correct types. If you try to pass in [UIControl], it doesn't have the shake method. If you try to pass in [UIButton], then the code compiles, but you can't pass in any UISliders. If you pass in [Shakeable], then you can't check control.state, because Shakeable doesn't have that. Swift 4 finally addressed the topic.
Old Answer
I am getting around this problem for the time being with the following code:
// This class is used to replace the UIViewController<UITableViewDelegate>
// declaration in Objective-C
class ConformingClass: UIViewController, UITableViewDelegate {}
class AClass: UIViewController {
#IBOutlet weak var anotherThing: UILabel!
var thing: ConformingClass!
}
This seems hackish to me. If any of the delegate methods were required, then I would have to implement those methods in ConformingClass (which I do NOT want to do) and override them in a subclass.
I have posted this answer in case anyone else comes across this problem and my solution helps them, but I am not happy with the solution. If anyone posts a better solution, I will accept their answer.
It's not the ideal solution, but you can use a generic function instead of a generic class, like this:
class AClass: UIViewController {
#IBOutlet weak var anotherThing: UILabel!
private var thing: UIViewController?
func setThing<T: UIViewController where T: UITableViewDelegate>(delegate: T) {
thing = delegate
}
}
I came across the same issue, and also tried the generic approach. Eventually the generic approach broke the entire design.
After re-thinking about this issue, I found that a protocol which cannot be used to fully specify a type (in other words, must come with additional type information such as a class type) is unlikely to be a complete one. Moreover, although the Objc style of declaring ClassType<ProtocolType> comes handy, it disregards the benefit of abstraction provided by protocol because such protocol does not really raise the abstraction level. Further, if such declaration appears at multiple places, it has to be duplicated. Even worse, if multiple declarations of such type are interrelated (possibly a single object will be passed around them ), the programme becomes fragile and hard to maintain because later if the declaration at one place needs to be changed, all the related declarations have to be changed as well.
Solution
If the use case of a property involves both a protocol (say ProtocolX) and some aspects of a class (say ClassX), the following approach could be taken into account:
Declare an additional protocol that inherits from ProtocolX with the added method/property requirements which ClassX automatically satisfy. Like the example below, a method and a property are the additional requirements, both of which UIViewController automatically satisfy.
protocol CustomTableViewDelegate: UITableViewDelegate {
var navigationController: UINavigationController? { get }
func performSegueWithIdentifier(identifier: String, sender: AnyObject?)
}
Declare an additional protocol that inherits from ProtocolX with an additional read-only property of the type ClassX. Not only does this approach allow the use of ClassX in its entirety, but also exhibits the flexibility of not requiring an implementation to subclass ClassX. For example:
protocol CustomTableViewDelegate: UITableViewDelegate {
var viewController: UIViewController { get }
}
// Implementation A
class CustomViewController: UIViewController, UITableViewDelegate {
var viewController: UIViewController { return self }
... // Other important implementation
}
// Implementation B
class CustomClass: UITableViewDelegate {
private var _aViewControllerRef: UIViewController // Could come from anywhere e.g. initializer
var viewController: UIViewController { return _aViewControllerRef }
... // UITableViewDelegate methods implementation
}
PS. The snippet above are for demonstration only, mixing UIViewController and UITableViewDelegate together is not recommended.
Edit for Swift 2+: Thanks for #Shaps's comment, the following could be added to save having to implement the desired property everywhere.
extension CustomTableViewDelegate where Self: UIViewController {
var viewController: UIViewController { return self }
}
you can declare a delegate in Swift like this:
weak var delegate : UITableViewDelegate?
It will work with even hybrid(Objective-c and swift) project. Delegate should be optional & weak because its availability is not guaranteed and weak does not create retain cycle.
You are getting that error because there are no generics in Objective-C and it will not allow you to add #IBOutlet property.
Edit: 1. Forcing a type on delegate
To force that delegate is always a UIViewController you can implement the custom setter and throw exception when its not a UIViewController.
weak var _delegate : UITableViewDelegate? //stored property
var delegate : UITableViewDelegate? {
set {
if newValue! is UIViewController {
_delegate = newValue
} else {
NSException(name: "Inavlid delegate type", reason: "Delegate must be a UIViewController", userInfo: nil).raise()
}
}
get {
return _delegate
}
}

Resources