I have an AS class with setter and getter functions.
I need to tweak one of this class's instances so that it's setter function will process the input before assigning it to the local variable.
or, in a more elaborated way, what should I use instead of $$$ in the example below?
class MyClass{
private var _legend:Array;
function set legend(legend:Array):void{
_legend= legend;
}
function get legend():Array{
return _legend;
}
function someFunction():void{
foo();
}
}
var mc:MyClass = new MyClass();
mc.someFunction = function():void{
bar();
}
mc.$$$ = new function(legend:Array):void{
_legend = process(legend);
}
Normally you would subclass MyClass to modify the behavior (polymorphism) of MyClass.
class MySubClass extends MyClass {
function set legend(legend:Array):void{
// do your checking here. Then call the
// setter in the super class.
super.legend = legend;
}
}
Why don't you pass the instance a processed input?
mc.legend = process(legend);
If this is not possible, you can modify the setter in MyClass and take an optional boolean to do processing.
function set legend(legend:Array, flag:bool = false):void{
_legend = flag ? process(legend) : legend;
}
Note that prototype inheritance does not restrict itself to a particular instance. From the documentation:
Prototype inheritance - is the only inheritance mechanism in previous versions of ActionScript and serves as an alternate form of inheritance in ActionScript 3.0. Each class has an associated prototype object, and the properties of the prototype object are shared by all instances of the class.
Related
I want to specify a constructor that does not change the default value of test.
So "test text" should be printed instead of null.
void main() async {
print(B().text);
}
class A{
A({this.text = "test text"});
final text;
}
class B extends A{
B({String text}) : super(text: text);
}
dartpad
Is this possible?
Not as such. If you write a constructor, you can't get the superclass constructor's default value automatically in any way, and you have to either pass the parameter to the superconstructor or not in the initializer list. It can't depend on the value of the subclass constructor's parameter. So, you have to write the superclass constructor parameter default value again.
The one hack you can do (and I don't recommend doing it just for this) is that if the parameters to the subclass constructor is exactly the same as the superclass constructor, you can declare the members of your subclass in a mixin and make the subclass be a mixin application.
So instead of:
class SuperClass {
SuperClass(...args) : ...
...
}
class SubClass extends SuperClass {
SubClass(...args) : super(...args);
members() ...
}
you do:
class SuperClass {
SuperClass(...args) : ...
...
}
mixin _SubClass on SuperClass {
members() ...
}
class SubClass = SuperClass with _SubClass;
That will give SubClass a constructor for each superclass constructor, with the same parameters (including default values), which forwards directly to the superclass constructor.
Don't do this just to avoid writing the default value again!
Problem I need to solve
Is there a way to get the class name of a dart class as a String or a Type object..?
class MyClass {
}
var myClass = MyClass();
I know the property, runtimeType which return the type of the object as a Type object. But is there a similar function for classes?
print(myClass.runtimeType.toString());
What I currently do is creating an object of the class and use runtimeType.
String type = MyClass().runtimeType.toString();
Note: In python there is a variable called __name__ in every class, which does what I need.
My intention
My final goal is to create dart objects using previously saved class names. In this issue they have proposed a method using Maps.
The thing is that I have lots of classes and that method looks messy in my situation.
What I currently do is, save the object type by:
var saving = myClass.runtimeType.toString();
And when loading:
if (saving == MyClass().runtimeType.toString()) {
return MyClass();
}
From your experiences and opinions, can you propose a better solution?
You can use:
var runtimeTypeName = (MyClass).toString();
or for generics:
var runtimeTypeName = T.toString();
The class type can be used as a Type:
Type myType = MyClass;
I have a rather simple question. How can I use variables from different classes in dart?
class ContainsVariable {
var variable = 1;
}
class DoesNotContainVariable {
var useVariable = variable + 1; // This gives me an error saying:
// Undefined name 'variable'
}
Having their own scope is a very fundamental feature of classes in Object Oriented Programming, corresponding to OOP principles.
Also note that from your code, it seems that you have not properly understood the idea of instantiation in Object Oriented Programming, since you are trying to set an instance variable without instantiating the class. I highly suggest to look into this topic to gain more understanding.
That being said, there are most definitely many ways to achieve what you want. Since your code sample is very general, I'm not exactly sure what you are trying to do, so I'll provide 2 examples, which might be useful:
Option 1 - static member variable
You can make a static (class level) member, which will be the same for all objects.
class ContainsVariable {
static var variable = 1;
}
class DoesNotContainVariable {
var useVariable = ContainsVariable.variable + 1; // here, you are using a
// static (class) variable,
// not an instance variable.
// That is why you are using
// the class name.
}
Option 2 - instantiation
You can instantiate the class - by creating an object of that class - and access the member of that object. Notice that there is no static statement here.
class ContainsVariable {
var variable = 1;
}
class DoesNotContainVariable {
var instanceOfContainsVariable;
var useVariable;
DoesNotContainVariable(){ // this is a constructor function
var instanceOfContainsVariable = new ContainsVariable();
useVariable = instanceOfContainsVariable.variable + 1;
}
}
I am struggling with the concept of getters and setters in Dart, and the more I read, the more I cannot grasp the underlying purpose. Take for example the following code:
main() {
Car car = new Car();
car.doors = 44;
print(car.doors); // 44
}
class Car {
int doors = 4;
}
Later, I decide to make “doors” a private variable, so I do the following:
main() {
Car car = new Car();
car.doors = 44;
print(car.doors); // 44
}
class Car {
int _doors = 4;
int get doors => _doors;
set doors(int numberOfDoors) => _doors = numberOfDoors;
}
According to the code, _doors is now a private variable, and so I cannot access it in main(). However, by manipulating doors, I can indirectly change the value of _doors, which is what I thought I wanted to prevent in the first place by making it a private variable. So what is the purpose of making a previously public variable into a private one, if you can still indirectly manipulate it? And, how are getters and setters even working to change the properties of these variables? I am trying to understand the fundamental concept, because without that, I don't understand how or why getters and setters are used.
Instance variables in Dart have implicit getters and setters. So for your example code, it will operate in exactly the same way, since all you have done is changed from an implicit getter and setter to an explicit getter and setter.
The value of explicit getters and setters is that you don't need to define both if you don't want. For instance we can change your example to only define a getter:
main() {
Car car = new Car();
print(car.doors); // 4
car.doors = 6; // Won't work since no doors setter is defined
}
class Car {
int _doors = 4;
int get doors => _doors;
}
Additionally, you can also add extra logic in a getter or setter that you don't get in an implicit getter or setter:
class Car {
int _doors = 4;
int get doors => _doors;
set doors(int numberOfDoors) {
if(numberOfDoors >= 2 && numberOfDoors <= 6) {
_doors = numberOfDoors;
}
}
}
The getter and setter functions allow us to make the class appear to have a property, without a explicit property being declared (_doors in your case). The property value may be calculated from other properties.
The getters and setters allow us to execute arbitrary code when the property is get or set.
Omitting a setter makes the property immutable.
An abstract class may declare getters and setters without bodies as part of a required class interface.
I'm looking for behavior similar to Objective-C's +(void)initialize class method, in that the method is called once when the class is initialized, and never again thereafter.
A simple class init () {} in a class closure would be really sleek! And obviously when we get to use "class vars" instead of "static vars in a struct closure", this will all match really well!
If you have an Objective-C class, it's easiest to just override +initialize. However, make sure subclasses of your class also override +initialize or else your class's +initialize may get called more than once! If you want, you can use dispatch_once() (mentioned below) to safeguard against multiple calls.
class MyView : UIView {
override class func initialize () {
// Do stuff
}
}
If you have a Swift class, the best you can get is dispatch_once() inside the init() statement.
private var once = dispatch_once_t()
class MyObject {
init () {
dispatch_once(&once) {
// Do stuff
}
}
}
This solution differs from +initialize (which is called the first time an Objective-C class is messaged) and thus isn't a true answer to the question. But it works good enough, IMO.
There is no type initializer in Swift.
“Unlike stored instance properties, you must always give stored type properties a default value. This is because the type itself does not have an initializer that can assign a value to a stored type property at initialization time.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
You could use a type property which default value is a closure. So the code in the closure would be executed when the type property (or class variable) is set.
class FirstClass {
class var someProperty = {
// you can init the class member with anything you like or perform any code
return SomeType
}()
}
But class stored properties not yet supported (tested in Xcode 8).
One answer is to use static, it is the same as class final.
Good link for that is
Setting a Default Property Value with a Closure or Function
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
Code example:
class FirstClass {
static let someProperty = {
() -> [Bool] in
var temporaryBoard = [Bool]()
var isBlack = false
for i in 1...8 {
for j in 1...8 {
temporaryBoard.append(isBlack)
isBlack = !isBlack
}
isBlack = !isBlack
}
print("setting default property value with a closure")
return temporaryBoard
}()
}
print("start")
FirstClass.someProperty
Prints
start
setting default property value with a closure
So it is lazy evaluated.
For #objc classes, class func initialize() definitely works, since +initialize is implemented by the Objective-C runtime. But for "native" Swift classes, you'll have to see the other answers.
You can use stored type properties instead of initialize method.
class SomeClass: {
private static let initializer: Void = {
//some initialization
}()
}
But since stored types properties are actually lazily initialized on their first access, you will need refer them somewhere. You can do this with ordinary stored property:
class SomeClass: {
private static let initializer: Void = {
//some initialization
}()
private let initializer: Void = SomeClass.initializer
}
#aleclarson nailed it, but as of recent Swift 4 you cannot directly override initialize. You still can achieve it with Objective-C and categories for classes inheriting from NSObject with a class / static swiftyInitialize method, which gets invoked from Objective-C in MyClass.m, which you include in compile sources alongside MyClass.swift:
# MyView.swift
import Foundation
public class MyView: UIView
{
#objc public static func swiftyInitialize() {
Swift.print("Rock 'n' roll!")
}
}
# MyView.m
#import "MyProject-Swift.h"
#implementation MyView (private)
+ (void)initialize { [self swiftyInitialize]; }
#end
If your class cannot inherit from NSObject and using +load instead of +initialize is a suitable fit, you can do something like this:
# MyClass.swift
import Foundation
public class MyClass
{
public static func load() {
Swift.print("Rock 'n' roll!")
}
}
public class MyClassObjC: NSObject
{
#objc public static func swiftyLoad() {
MyClass.load()
}
}
# MyClass.m
#import "MyProject-Swift.h"
#implementation MyClassObjC (private)
+ (void)load { [self swiftyLoad]; }
#end
There are couple of gotchas, especially when using this approach in static libraries, check out the complete post on Medium for details! ✌️
I can't find any valid use case to have something like +[initialize] in Swift. Maybe this explains way it does not exist
Why do we need +[initialize] in ObjC?
To initialize some global variable
static NSArray *array;
+ (void)initialize {
array = #[1,2,3];
}
which in Swift
struct Foo {
static let array = [1,2,3]
}
To do some hack
+ (void)initialize {
swizzle_methodImplementation()
}
which is not supported by Swift (I can't figure out how to do it for pure Swift class/struct/enum)