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;
}
}
Related
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;
Is there any semantic difference between class-level and member-level self-identifiers in F#? For example, consider this class:
type MyClass2(dataIn) as self =
let data = dataIn
do
self.PrintMessage()
member this.Data = data
member this.PrintMessage() =
printfn "Creating MyClass2 with Data %d" this.Data
Versus this class:
type MyClass2(dataIn) as self =
let data = dataIn
do
self.PrintMessage()
member this.Data = data
member this.PrintMessage() =
printfn "Creating MyClass2 with Data %d" self.Data
The only difference is that the implementation of PrintMessage references this in one vs. self in the other. Is there any difference in semantics? If not, is there a stylistic reason to prefer one over the other?
There's no real semantic difference between the two. As a rule of thumb, I suggest going with your first example - prefer the identifier that's closer in scope, it makes it easier to read and refactor the code later. As a side note, people will usually use this both for class and member-level identifiers, in which case the member-level one shadows class-level one.
In these kind of scenarios, it's useful to look at the compiled code in a disassembler like ILSpy. If you do that, you'll find that the only difference is an extra null check that is inserted in self.Data case.
On the other hand, there is a difference between a class that uses a class-level identifier and one that doesn't (a series of initialization checks get inserted into all the class members). It's best to avoid having them if possible, and your example can be rewritten to not require one.
As mentioned by scrwtp, this seems to be a commonly used identifier and it is my preference. Another very common one is x. I tend to use the class-level identifier when it's used multiple times throughout a class and of course when it's used in the constructor. And in those cases I would use __ (two underscores) as the member level identifier, to signify that the value is ignored. You can't use _ and actually ignore it as it's a compile error, but linting tools will often consider __ as the same thing and avoid giving you a warning about an unused identifier.
When you add a class-level identifier and don't use it you get a warning:
The recursive object reference 'self' is unused. The presence of a recursive object reference adds runtime initialization checks to members in this and derived types. Consider removing this recursive object reference.
Consider this code:
type MyClass() =
member self.X = self
type MyClassAsSelf() as self =
member __.X = self
type MyClassAsSelfUnused() as self = // <-- warning here
member __.X = ()
This is what these classes look like after compiling/decompiling:
public class MyClass
{
public Program.MyClass X
{
get
{
return this;
}
}
public MyClass() : this()
{
}
}
public class MyClassAsSelf
{
internal FSharpRef<Program.MyClassAsSelf> self = new FSharpRef<Program.MyClassAsSelf>(null);
internal int init#22;
public Program.MyClassAsSelf X
{
get
{
if (this.init#22 < 1)
{
LanguagePrimitives.IntrinsicFunctions.FailInit();
}
return LanguagePrimitives.IntrinsicFunctions.CheckThis<Program.MyClassAsSelf>(this.self.contents);
}
}
public MyClassAsSelf()
{
FSharpRef<Program.MyClassAsSelf> self = this.self;
this..ctor();
this.self.contents = this;
this.init#22 = 1;
}
}
public class MyClassAsSelfUnused
{
internal int init#25-1;
public Unit X
{
get
{
if (this.init#25-1 < 1)
{
LanguagePrimitives.IntrinsicFunctions.FailInit();
}
}
}
public MyClassAsSelfUnused()
{
FSharpRef<Program.MyClassAsSelfUnused> self = new FSharpRef<Program.MyClassAsSelfUnused>(null);
FSharpRef<Program.MyClassAsSelfUnused> self2 = self2;
this..ctor();
self.contents = this;
this.init#25-1 = 1;
}
}
Note that there is a check that a variable has been set in the constructor. If the check fails then a function is called: LanguagePrimitives.IntrinsicFunctions.FailInit(). This is the exception thrown:
System.InvalidOperationException: The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized.
I guess the warning is there just so that you can avoid the slight overhead of an unnecessary runtime check. However, I don't know how to construct a situation where the error is thrown, so I don't know the exact purpose of the check. Perhaps someone else can shed light on this?
Please help me with Swift,
I need singleton with can inheritance.
I can do like this
class A {
var defaultPort: Int
required init() {
self.defaultPort = 404
}
class var defaultClient: A {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: A? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = self.init()
}
return Static.instance!
}
}
but in swift 2.0 we can do like this
static let defaultClient = A() //self.init()
but it creates an instance of the class A any way.
How i can use like this self.init()
static let defaultClient = self.init()
in order to be able to inherit
UPD
best way for now
class A {
class func defaultClient() -> Self {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: A? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = self.init()
}
return instance(Static.instance, asType: self)
}
}
here we need helper as
func instance<T>(instance: Any, asType type: T.Type) -> T {
let reurnValue = instance as! T
return reurnValue
}
because another way cast A to Self not exist, for now.
p.s. crazy swift way!
why i can not do instance as! Self
Your question isn't very clear. You're looking for something like the class constant solution posted in this answer, but which automatically uses "my own class" instead of explicitly creating an instance of a specific class... right?
That is, you want to turn this:
class Singleton {
static let sharedInstance = Singleton()
}
into this:
class Singleton {
static let sharedInstance = SomeMagicThing()
}
class SingletonSubclass {}
where SomeMagicThing automatically creates a Singleton instance when you call Singleton.sharedInstance, and a SingletonSubclass instance when you call SingletonSubclass.sharedInstance. Correct?
Sorry, that can't be done (as of Swift 2.1).
Part of your issue is that static and class mean two different things. The static modifier means that the declaration it modifies is associated only with a specific type declaration. So, the Singleton type owns a pointer to a specific object -- its subclasses don't inherit that pointer. (And if they did, would it point to the same object or a subclass-specific one?)
If you could create a class var or class let, that'd (in theory) give you the kind of dispatch/inheritance you want. But trying that gives you an error (emphasis mine):
class stored properties not yet supported in classes; did you mean static?
So it sounds like this sort of thing might show up someday.
Of course, the other side of the problem is finding a way to dynamically refer to the "current" type responsible for executing some statement. In the context of an instance method, you have self.dynamicType for such things... but there's no equivalent for classes. (Self is a type constraint, not an actual type.) This is a side effect of the type system in Swift being much more strict and static than that of Objective-C (for example, metatypes aren't just a special flavor of otherwise normal objects). File a bug if you'd like to see a change to that effect?
I have the following class:
class FeedDataManager: URLManagerdelegate {
let TAG: String = "FeedDataManager"
weak var mDelegate: KeyboardViewController?
var mModelManager: ModelManager!
var mURLManager: UrlManager!
var mGetNewsTimer: NSTimer?
var mFeedsArray: Array<News>!
var mManagedObjectContext: NSManagedObjectContext!
var mPersistentStoreCoordinator: NSPersistentStoreCoordinator!
var mManagedObjectModel: NSManagedObjectModel!
class var sharedInstance: FeedDataManager {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: FeedDataManager? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = FeedDataManager()
}
return Static.instance!
}
init (aDelegate: KeyboardViewController) {
self.mDelegate = aDelegate
}
}
The Problem: If you look at the init method you will see that it should receive as a parameter a delegate pointer that I want to store in the singleton, so basically I need to pass this parameter to this line:
Static.instance = FeedDataManager()
But I have no idea how it's done, Does any knows how this can be done?
BTW: I saw this link:
Singleton and init with parameter
But the singleton creation there is different.
We can show you how you can add parameter to declaration of singleton, but that's not really a good idea. The entire idea behind a singleton is that it doesn't matter where it is instantiated, you can use it anywhere. What does it mean if you invoked this singleton in two different places in your code, with different parameters? You have a race condition, where the behavior may change depending upon where and how the singleton was first encountered.
Unrelated, but the dispatch_once is redundant. The static variables are already employed with dispatch_once. See discussion at end of http://developer.apple.com/swift/blog/?id=7 (this is primarily geared towards globals, but as they parenthetically point out, it applies to static variables, too). Also, in Swift 1.2, we can now have static class variables, eliminating the need for the struct, too
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.