Swift generic inheritance - swift

I have one base view controller and some child view controllers. I am having difficulty to pass the view model created in children view controller (CommentViewController) to it's parent view controller (FeedBaseViewController) to access.
class BaseViewController: UIViewController {
...
}
class FeedBaseViewController: BaseViewController {
var viewModel1 = FeedBaseViewModel<BaseObject>()
...
}
class CommentViewController: FeedBaseViewController {
var viewModel2: CommentViewModel<CommentObject>
init() {
viewModel2 = CommentViewModel()
/* This is where I have issue, and I tried a few approaches. And here are the 2 of them.*/
// Method 1:
// viewModel1 = viewModel2
// Error: Cannot assign value of type 'CommentViewModel<CommentObject>' to type 'FeedBaseViewModel<BaseObject>'
// Method 2:
// viewModel1 = viewModel2 as FeedBaseViewModel<BaseObject>
// Error: Cannot convert value of type 'CommentViewModel<CommentObject>' to type 'FeedBaseViewModel<BaseObject>' in coercion
...
}
...
}
My view models for the View Controller
class FeedBaseViewModel<Item: BaseObject> {
}
class CommentViewModel<T: CommentObject>: FeedBaseViewModel<CommentObject> {
}
Here are the object classes, the BaseObject class is the only Objective-C class here, and a CommentObject swift class which inherit from BaseObject.
#interface BaseObject : NSObject <NSCoding>
#end
class CommentObject: BaseObject {
}
I am not sure if it is possible to do, or it is only syntax issue.
Please advice, thank you!
Edited(2017-09-11):
I think I could provide more information of what I would like to achieve, and hope it helps.
FeedBaseViewModel stores and manipulate an array of items with type BaseObject.
FeedBaseViewController have UI handling actions such as "filtering", "sorting", and ask FeedBaseViewModel to do the job.
For the Comment part, I will have a CommentObject array with basic manipulation and some specific manipulation. This is why CommentViewModel comes in, CommentViewModel inherit FeedBaseViewModel so that basic manipulation can be handled by the parent, and it will do the specific manipulation itself.
Similar in the view controller part, CommentViewController will inherit FeedBaseViewController, so FeedBaseViewController can do the basic handling while CommentViewController itself can provide additional functions.

I do not think that is possible.
Your problem boils down to:
let m = FeedBaseViewModel<CommentObject>()
let k : FeedBaseViewModel<BaseObject> = m
That is not allowed. As to why: assume that FeedBaseViewModel contains a member of its generic type and offers a set function for that member. If you now would be allowed to write the second line, then call set using a BasObject instance that would violate the generic constraint of m because they are still the same object instance with different generic constraints, a BaseObject instance is not necessarily an instance of CommentObject.
A solution in your case should be to move the generics up a little bit more:
class FeedBaseViewController<T : BaseObject>: BaseViewController {
var viewModel1: FeedBaseViewModel<T>
required init?(coder aDecoder: NSCoder) {
viewModel1 = FeedBaseViewModel<T>()
super.init(coder: aDecoder)
}
}
class CommentViewController: FeedBaseViewController<CommentObject> {
var viewModel2: CommentViewModel<CommentObject>
required init?(coder aDecoder: NSCoder) {
viewModel2 = CommentViewModel<CommentObject>()
super.init(coder: aDecoder)
viewModel1 = viewModel2
// now this assignment is allowed because viewModel1 and viewModel2 have the super type FeedBaseViewModel<CommentObject>
}
}
Not sure if that solution works in your situation though.

Related

Swift: Init() Pattern for Parent/Child Relationship

Setup
Suppose I have two classes:
final class Parent: NSObject
{
var child: Child
}
final class Child: NSObject
{
weak var parent: Parent?
init(parent: Parent)
{
self.parent = parent
}
}
Question:
Now suppose that I want to instantiate a child and establish this relationship in the init() method of Parent. I would do this:
final class Parent: NSObject
{
var child: Child
init()
{
child = Child.init(parent: self) // ERROR!
}
}
Swift whines that I'm using self before super.init(). If I place super.init() before I instantiate child, Swift whines that child isn't assigned a value at the super.init() call.
I've been shutting Swift up by using implicitly-unwrapped optionals, like this:
final class Parent: NSObject
{
var child: Child!
init()
{
super.init()
child.init(parent: self)
}
}
My question is: What do people do in this situation? This is/was a VERY common pattern in Objective-C and Swift produces nothing but headaches. I understand that I could de-couple the assignment of parent from Child's init() so that I could init() child, call super.init(), and then assign parent, but that is not an option in the real-world cases where I run into this. It's also ugly and bloated.
I do realize Swift's intent is to prevent use of an object before it is fully initialized. And that it's possible for child's init() to call back to parent and access state that isn't set up yet, which becomes a danger with the implicitly-unwrapped optional approach.
I cannot find any guidance about Swift best practice here, so I'm asking how people resolve this chicken-and-egg issue. Is turning properties into implicitly unwrapped optionals really the best way around this limitation? Thanks.
You can make it lazy and all your headaches will gone!
final class Parent {
lazy var child = Child(parent: self)
}
final class Child {
weak var parent: Parent?
init(parent: Parent) {
self.parent = parent
}
}
In Swift, all stored properties should be initialized before self is available. Including stored properties in the superclass. So Xcode doesn't let you use self till then. But using lazy means that it is initialized before. So you can use self freely.
Some helpful notes:
Don't inherit from NSObject if you don't need objc advanced features for your class.
In swift naming convention, open parentheses ( will read as with in objective-C. So you don't need withParent as a label in your initializer.
Use internal and external naming of arguments as the convention suggests.
Also note that some of the above notes are written before comments

Swift Required initializers in EVReflection

I'm writing code in Swift, and using https://github.com/evermeer/EVReflection. However, Xcode is playing shenanigans with my class structure - in a few places, it claims I need to include a required initialized, declared in EVObject, but not in other places. Consider the following example:
class Root: EVObject {
}
class MidA: Root {
required init() {
}
init(blah: String) {
}
}
class LeafA: MidA {
required init() {
super.init()
}
} // Error: 'required' initializer 'init(coder:)' must be provided by subclass of 'EVObject'
class MidB: Root {
required init() {
}
}
class LeafB: MidB {
required init() {
super.init()
}
} // No error
EVObject contains the following method definition:
public convenience required init?(coder: NSCoder) {
self.init()
EVReflection.decodeObjectWithCoder(self, aDecoder: coder, conversionOptions: .DefaultNSCoding)
}
Describing the example in words, there's a root object, Root, which extends EVObject, and it forks into two subclasses, MidA and MidB, which each have a subclass of their own: LeafA and LeafB. LeafA and LeafB are identical aside from their name and superclass. MidA and MidB differ only in name and in that MidA has an additional initializer that takes a parameter.
What bearing could that possibly have on LeafA? Having an extra initializer with a parameter seems entirely unrelated to the particular initializer declared in EVObject (which is apparently required, but it's not usually enforced??). Why would adding an unrelated initialized in a branch class suddenly require me, in my leaf classes, to figure out what the heck is this required initializer I've never seen before?
It's indeed caused by the extra init
init(blah: String) {
}
That one could also be changed to:
convenience init(blah: String) {
self.init()
}
Then it won't complain about adding the required initializer.
With the convenience you specify that you will call a required initializer from there. Without that the compiler can't be sure that you do.
See also https://docs.swift.org/swift-book/LanguageGuide/Initialization.html

questions about super.init and ()

I am confused when you have a child class that inherit from a parent class.
First question is why use super.init? I understand override init so it can override the values that was previously set from the parent but I don't understand the use of super.init..
Second question is why does init have parameters?
EDIT: Also why sometimes, the parent class also have a init??
class car {
var speed = 5
var model: String?
var age: Int?
}
class bmw: car {
override init() {
super.init()
model = "cat"
}
}
In your example, there is no good reason for calling super. But in general any class may have properties to initialize and other initial tasks to perform, and the rule, which says that a designated initializer of a subclass must call a superclass designated initializer, guarantees that this will happen coherently both for the subclass and for the superclass.

Why use required Initializers in Swift classes?

I am trying to understand the use of the required keyword in Swift classes.
class SomeClass
{
required init() {
// initializer implementation goes here
}
}
required doesn't force me to implement the method in my child-class. If I want to override the required designated initializer of my parent class I need to write required and not override. I know how it works but can not understand why I should do this.
What is the benefit of required?
As far as I can tell, languages like C# don't have something like this and work just fine with override.
It's actually just a way of satisfying the compiler to assure it that if this class were to have any subclasses, they would inherit or implement this same initializer. There is doubt on this point, because of the rule that if a subclass has a designated initializer of its own, no initializers from the superclass are inherited. Thus it is possible for a superclass to have an initializer and the subclass not to have it. required overcomes that possibility.
One situation where the compiler needs to be satisfied in this way involves protocols, and works like this:
protocol Flier {
init()
}
class Bird: Flier {
init() {} // compile error
}
The problem is that if Bird had a subclass, that subclass would have to implement or inherit init, and you have not guaranteed that. Marking Bird's init as required does guarantee it.
Alternatively, you could mark Bird as final, thus guaranteeing the converse, namely that it will never have a subclass.
Another situation is where you have a factory method that can make a class or its subclass by calling the same initializer:
class Dog {
var name: String
init(name: String) {
self.name = name
}
}
class NoisyDog: Dog {
}
func dogMakerAndNamer(whattype: Dog.Type) -> Dog {
let d = whattype.init(name: "Fido") // compile error
return d
}
dogMakerAndNamer is calling the init(name:) initializer on Dog or a Dog subclass. But how can the compiler be sure that a subclass will have an init(name:) initializer? The required designation calms the compiler's fears.
According to the documentation:
Write the required modifier before the definition of a class initializer to
indicate that every subclass of the class must implement that initializer
So yes, required does force all child classes to implement this constructor. However, this is not needed
if you can satisfy the requirement with an inherited initializer.
So if you have created more complex classes that cannot be fully initialized with a parent constructor, you must implement the require constructor.
Example from documentation (with some added stuff):
class SomeClass {
required init() {
// initializer implementation goes here
}
}
class SomeSubclass: SomeClass {
let thisNeedsToBeInitialized: String
required init() {
// subclass implementation of the required initializer goes here
self.thisNeedsToBeInitialized = "default value"
}
}
I want to draw an attention on another solution provided by Required, apart from Matt has given above.
class superClass{
var name: String
required init(){
// initializer implementation goes here
self.name = "Untitled"
}
}
class subClass: superClass {
var neakName: String = "Subclass Untitled"
}
let instanceSubClass = subClass()
instanceSubClass.name //output: "Untitled"
instanceSubClass.neakName //output: "Subclass Untitled"
As you can check in above example, I've declared required init() on superClass, init() initializer of superClass has inherited by default on subClass, So you able to create an instance of subClass let instanceSubClass = subClass().
But, suppose you want to to add one designated initializer on subClass to assign run time value to stored property neakName. Of course you can add it, but that will result to no initializers from the superClass will be inherited to subClass, So if you will create an instance of subClass you will create through its own designated initializer as below.
class superClass{
var name: String
init(){
// initializer implementation goes here
self.name = "Untitled"
}
}
class subClass: superClass {
var neakName: String = "Subclass Untitled"
init(neakName: String) {
self.neakName = neakName
}
}
let instanceSubClass = subClass(neakName: "Bobby")
instanceSubClass.name //output: "Untitled"
instanceSubClass.neakName //output: "Bobby"
Here above, you won't be able to create an instance of subClass by just subClass(), But if you want that every subclasses of superClass must have their own init() initializer to create direct instance by subClass(). Just place required keyword before init() on superClass, it will force you to add init() initializer on subClass too - as below.
class superClass{
var name: String
required init(){
// initializer implementation goes here
self.name = "Untitled"
}
}
class subClass: superClass {
var neakName: String = "Subclass Untitled"
init(neakName: String) {
self.neakName = neakName
}
} // Compiler error <------------ required `init()` must be provided by subClass.
let instanceSubClass = subClass(neakName: "Bobby")
instanceSubClass.name //output: "Untitled"
instanceSubClass.neakName //output: "Bobby"
SO, use required keyword before initializer on superclass, when you want all subclasses must have been implemented required initializer of superclass.
If you are trying to add you own initialiser in the sub class, then you have to follow certain things those were declared in super class. So it make sure that you will not forget to implement that required method. If you forget compiler will give you error // fatal error, we've not included the required init()
. Another reason is it creates a set of conditions that ever sub class should follow it the sub class is defining its own initialiser.

Non-optional var in swift UIViewController subclass

import Foundation
import RentalsService
class RentalsViewController: UIViewController {
var rentalService: Rentals
init(rentalService: Rentals) {
self.rentalService = rentalService
super.init(nibName: "RentalsViewController", bundle: NSBundle.mainBundle())
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder) // problem here
}
}
I want rentalService variable to be non-optional. i.e. you can't have a rentalsVC without the service. However, I'm forced to declare init(NSCoder) - but I don't have access to a rental service implementation at this point.
Rentals is a protocol, and I'm using dependency injection - so one doesn't create the dependency inside the class.
Anyone got any clever ideas to overcome this? Or what is the preffered pattern / best practice?
You can do this if you don't want to support NSCoding:
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
As referenced here: https://stackoverflow.com/a/25128815/2611971
Depending on which DI framework you're using, the way I'd fix it is by using setter injection rather than constructor injection.
In that case you have to either provide an initial fake value to the property at initialization time, or convert the property to optional. In the latter case, I'd declare it as implicitly unwrapped:
var rentalService: Rentals!
to avoid unwrapping it explicitly at every usage.
Another solution, which I am using in my own DI framework, is to initialize properties lazily and inline, for example:
private lazy var _router: IRouter = { Injector.instance.instanceForType(IRouter.self) as IRouter }()
Here I know the interface, and I ask the injector to provide me an instance of whichever the bound type is. During app initialization I link interfaces to implementation statically.