Using final for subclass in swift - swift

I have two class A , B. B is the subclass of A. Can I use final for class B. I want to reduce the dynamic dispatch. What if there is method in class b that is overriding the class A method . How method dispatching will work?
class A {
///
}
final class B : Class A {
}

Yes, You can
Swift gives us a final keyword just for this purpose: when you declare a class as being final, no other class can inherit from it. This means they can’t override your methods in order to change your behavior – they need to use your class the way it was written.
The final keyword is a restriction on a class, method, or property that indicates that the declaration cannot be overridden. This allows the compiler to safely elide dynamic dispatch indirection.
So you can use it.

Related

Can a class be Sendable if it holds a reference to a non-Sendable singleton?

Suppose I have a class whose only state is a reference to a singleton class:
class MyClass {
let networkHelper: NetworkHelper
func makeNetworkRequest(_ url: URL) {
networkHelper.actuallyMakeNetworkRequest(url)
}
}
The NetworkHelper class is not Sendable; it maintains some mutable state (although that state is mostly invisible to outside callers). However, the class is a singleton and so any two instances of MyClass will always hold references to the same NetworkHelper.
Given that MyClass contains no mutable state of its own, and that it does hold a reference to a non-Sendable class instance, does MyClass conform to Sendable?
In short, because NetworkHelper is not Sendable, MyClass cannot be Sendable either. The fact that NetworkHelper is a singleton is immaterial.
FWIW, the compiler will help you out here: If you attempt to make MyClass conform to Sendable (by making it final and adding Sendable conformance), the compiler will tell you about the issue with NetworkHelper not being Sendable:
final class MyClass: Sendable {
let networkHelper: NetworkHelper = .shared // Stored property 'networkHelper' of 'Sendable'-conforming class 'MyClass' has non-sendable type 'NetworkHelper'
func makeNetworkRequest(_ url: URL) {
networkHelper.actuallyMakeNetworkRequest(url)
}
}
For MyClass to be Sendable, you will need to make NetworkHelper conform to Sendable, too.
FWIW, if NetworkHelper has a mutable state, you probably want to make it threadsafe, anyway, and once you do that, making it Sendable, too, is easy.
From documentaion
Sendable Classes To satisfy the requirements of the Sendable protocol,
a class must:
Be marked final
Contain only stored properties that are immutable and sendable
Have no superclass or have NSObject as the superclass
Classes marked with #MainActor are implicitly sendable, because the
main actor coordinates all access to its state. These classes can have
stored properties that are mutable and nonsendable.
Classes that don’t meet the requirements above can be marked as
#unchecked Sendable, disabling compile-time correctness checks, after
you manually verify that they satisfy the Sendable protocol’s semantic
requirements.
According to this, to be sendable
Your MyClass should be final
Your singleton, networkHelper should be immutable and sendable
Should have no superclasses [Which already is]

generics not able to use functions of superclass in dart/flutter

I have a problem with the syntax in Dart. I want to be able to use a constructor on a generic class. So I let the generic class extend an abstract class which has the specified constructor. But the Code still shows me that it's not working. Does anyone have an idea?
T fetchItem<T extends JsonModel>(){
return T.fromJson();
// This line shows the error
// The method 'fromJson' isn't defined for the type 'Type'.
}
abstract class JsonModel {
JsonModel.fromJson();
}
The following solution works, but I think it's extremly ugly:
T fetchItem<T extends JsonModel<T>>(T t){
return t.fromJson();
}
abstract class JsonModel<T> {
T fromJson();
}
Constructors are not inherited. Just because a base class has a certain constructor, does not mean the derived class has that constructor.
It doesn't have anything to do with generics. If you extended a class X from your JsonModel, it simply would not have a constructor of that name.

The instance member 'a' can't be accessed in an initializer [duplicate]

In Dart, is there a difference in assigning values right away vs in constructor like in Java?
class Example {
int x = 3;
}
vs
class Example {
int x;
Example() {
x = 3;
}
}
I ask because when I was using Flutter and tried to assign a Function that uses setState to a variable, it was not possible with the former method but possible with the latter.
In your trivial case, it doesn't matter.
In general, you can initialize instance variables in a few ways:
Inline (field initializers)
class Example1 {
T x = value;
}
Advantages:
Direct, concise.
Member will be initialized in all constructors.
Can be used to initialize final or non-nullable members.
Member is initialized before invoking base class constructors, which is important when the base class constructor calls member functions that are overridden by the derived class.
Disadvantages:
Cannot depend on construction arguments.
Usually cannot depend on this since the initialization occurs before this becomes valid (i.e., cannot depend on other instance members). (An exception is if the member is initialized lazily by declaring it late. This requires the null-safety feature to be enabled.)
Initializer list
class Example2 {
T x;
Example2() : x = value;
}
Advantages:
Can be used to initialize final or non-nullable members.
Member is initialized before invoking base class constructors, which is important when the base class constructor calls member functions that are overridden by the derived class.
Can utilize construction arguments.
The initialized variable always refers to a member variable, never to a constructor parameter.
Disadvantages:
If the class has multiple constructors, initialization would need to be duplicated, or constructors should redirect to a common constructor.
Cannot depend on this since the initialization occurs before this becomes valid (i.e., cannot depend on other instance members).
Can initialize only members of the enclosing class. Because initializer lists are executed before invoking base class constructors, they cannot set base class members.
Constructor body
class Example3 {
T x;
Example3() {
x = value;
}
}
Advantages:
Can utilize construction arguments.
Can be used to perform more complicated initialization, such as cases where the member cannot be initialized via a single expression.
Can use this (i.e., can use other instance members).
Can be used to set base class members.
Disadvantages:
Cannot be used to initialize non-late final nor non-nullable members.
If the class has multiple constructors, initialization would need to be duplicated or initialization code would need to be refactored out (such as, but not limited to, redirecting to a common constructor).
Member is initialized after invoking base class constructors.
If the constructor has a parameter that shadows a member variable, it's easy to accidentally refer to the parameter instead of the member. (See https://github.com/dart-lang/linter/issues/2552 for details.)
There probably are some points I'm forgetting, but I think that should cover the main ones.
Direct, inline initialization occurs first, then initialization lists, then constructor bodies. Also see Difference between assigning the values in parameter list and initialiser list, which explains why this becomes valid only for the later stages of object initialization.
As an example where it matters where members are initialized:
class Base {
Base() {
doSomething();
}
void doSomething() {}
}
class DerivedEarly extends Base {
int? x;
DerivedEarly() : x = 42;
#override
void doSomething() => print(x);
}
class DerivedLate extends Base {
int? x;
DerivedLate() {
x = 42;
}
#override
void doSomething() => print(x);
}
void main() {
DerivedEarly(); // Prints: 42
DerivedLate(); // Prints: null
}

Nested Generic in Swift

To put it simple, i have a generic class Class1<X:Class2<Y>>, and as far as i see Swift forces me to hardcode Y type in declaration of Class1, but i need Y to be variable as well as X.
Long version
I have a generic class DataSource<T:GenericItem> class, which is than subclassed by non generic implementations (like ItemsDataSource:DataSource<Item>).
Now I want to create a some generic controller which can work with subclasses of my generic DataSource.
So I'm declaring controller like this TableViewController<DS:GenericDataSource<GenericItem>>, but in this case I'm not able to subclass it with DataSource parameter that is
a subclass of GenericItem as it's own parameter (i.e. i can not declare SuperTableViewController<ItemsDataSource>, because ItemsDataSource has Item generic parameter and not its parent GenericItem).
Any idea how can i create such generic controller?
Maybe something like this will work:
class Class2<Y> { }
class Class1<X, Y where X: Class2<Y>> { }

Haxe java.lang.Object Equivalent

Haxe allows class inheritance hierarchies
class Honda extends Car {
...
}
is there a common inheritance hierarchy root for all objects? I have a generic container class that could contain any object and I want to be able to declare
var _contents:Object; //Any class instance in _contents
How can I do this?
You can also use {} as a type, which will accept class instances as well as anonymous objects :
var _contents:{};
We also have Dynamic, which basically means "anything" (not only objects, but also primitives like Bool, Int, etc).
If your class is a generic container, you may want to type its content, though, using type parameters:
class Container<T> {
var _contents:T;
public function new(contents:T):Void {
_contents = contents;
}
}
And then:
var arrayContainer = new Container([]);
var stuffContainer = new Container({foo:"bar"});
var classContainer = new Container( new Stuff() );
The inheritance root for classes is Class<T> so the following should work:
var _contents:Class<T>;
However, to store an Enum, you would have to use Enum<T> instead.
From the manual:
There is a special type in Haxe which is compatible with all classes:
Define: Class<T>
This type is compatible with all class types which means that all classes (not their instances) can be assigned to it. At compile-time, Class<T> is the common base type of all class types. However, this relation is not reflected in generated code.
This type is useful when an API requires a value to be a class, but not a specific one. This applies to several methods of the Haxe reflection API.