Dart. Late initialize final variables - dart

Is there way to late initialize for final variables. The problem is many values initialized with entry point to the class, which is not constructor. Hence they cannot be final right now. But in scope of particular class they will not be changed. For ex.
Controller controller;
double width;
void setup(final itemWidth) {
controller = MyController();
width = itemWidth;
}
Could it be possible? Right now I see only solution as a annotation. You might think it's for visual effect. But in fact it helps to avoid unpredictable flow during testing.

It is now possible to late initialize variables. For more information see Dart's documentation. The text below is copied from Dart's documentation:
Late final variables
You can also combine late with final:
// Using null safety:
class Coffee {
late final String _temperature;
void heat() { _temperature = 'hot'; }
void chill() { _temperature = 'iced'; }
String serve() => _temperature + ' coffee';
}
Unlike normal final fields, you do not have to initialize the field in its declaration or in the constructor initialization list. You can assign to it later at runtime. But you can only assign to it once, and that fact is checked at runtime. If you try to assign to it more than once — like calling both heat() and chill() here — the second assignment throws an exception. This is a great way to model state that gets initialized eventually and is immutable afterwards.

Related

how is it more efficient to use final/const instead of var?

final/const are nice to keep a variable's value from changing, but is it more efficient to use than using var to declare the variable? I wasn't able to find if i gain any efficiency by using final/const over using var.
Ok, let me try to explain.
class Foo {
var bar = 4;
function doSomething() {
return 3 + bar;
}
}
Must compute an addition everytime doSomething is called at runtime, because "bar" might change. If bar is final, the compiler can compute at compiletime. After all the remaining is something like:
class Foo {
// compiler erased "bar" and substituted any occurence by the value
function doSomething() {
return 7; // nothing to be computed at runtime
}
}
Note: most compilers detect a privat var as const, if it is never changed within its scope. But if the field is public, the compiler still won't know.

How to set a NSManaged variable?

I have a NSManagedObject class with two relationships: courseAand courseB.
These relationships should be represented in a dynamic variable. How is it possible to change this variable from outside the class?
#objc(Universtity)
public class Universtity: NSManagedObject {
dynamic var name: String {
get {
let name = self.courseA?.name
return name!
}
}
}
For example from within a ViewController like University.name = University.courseB.name ?
I was thinking about a Notifikation, but this seems maybe a little more complicated as it could be.
And if there is no other way, how should I implement the observer inside the University class?
Thank you for every idea.
Looking at your code, you have declared a "computed" or "ready-only" variable. This is a variable whose value comes from another variable or combination of variables.
I can't see your data model, so it's not clear if you have defined a name parameter in the Core Data model. Regardless, if you have the logic is somewhat confused, because the getter you have defined means any value it may hold would be ignored anyway. You would need to define a setter to set self.courseA.name if you want to ensure the value can be written to. You don't need to worry about key-value coding notifications, because they will be triggered by the Core Data Managed Object.
public class Universtity: NSManagedObject {
dynamic var name: String {
get {
let name = self.courseA?.name
return name!
}
set(newValue) {
courseA!.name = newValue
}
}
}
Also the pattern you have used to force unwrap a non-optional value in your getter isn't optimal. I haven't edited this because that is another discussion, but I would suggest asking yourself the question am I sure why I am doing this? for every "?" and "!" you use.

Why does referencing .self work instead of type.sharedInstance?

I have some code like this:
class miniUser {
///The shared instance of miniUser.
static let SI = miniUser()
init()
{
self.currentUser = self.getCurrentProfile()! as String
self.refreshUserList()
}
...
}
That code works fine. However, this code using the shared instance...
class miniUser {
///The shared instance of miniUser.
static let SI = miniUser()
init()
{
miniUser.SI.currentUser = miniUser.SI.getCurrentProfile()! as String
miniUser.SI.refreshUserList()
}
...
}
That does not work. In fact, it doesn't even spit out an error during runtime, it just freezes at 0 fps (I'm using SpriteKit) when another part of the code tries to initialize it.
Ideally, both versions of the code should mean the same thing.
Could anyone explain to me why using self.function() works instead of type.sharedInstance.function() during initialization? I'm not sure about it and need an explanation to understand what is happening here.
Any help is-- err, any explanations are appreciated.
The definition let SI = miniUser() will call the init() of your class in order to create the shared instance. However, init() is trying to access the shared instance miniUser.SI, so this is a recursive definition. It probably shouldn't be allowed at all by the compiler — I'd suggest filing a bug. If you need to modify instance variables during initialization, that's what self. is for. (In fact, you can leave out self. because it's implied.)

initializing class properties before use in Swift/iOS

I'm having trouble grasping the proper way of instantiating variables that always need to be set before an object is fully functional but may need to be instantiated after the constructor. Based on Swift's other conventions and restrictions it seems like there is a design pattern I'm unaware of.
Here is my use case:
I have a class that inherits from UIViewController and will programmatically create views based on user actions
I need to attach these views to this class, but to do so I need to retrieve their content based on configuration data supplied by another controller
I don't care if this configuration data is passed to the constructor (in which case it would always be required) or supplied by a secondary call to this object before it is used
My problem seems to be that both of the approaches in bullet 3 seem flawed.
In the first case, there is only one legitimate constructor this class can be called with, yet I'm forced to override other constructors and initialize member variables with fake values even if the other constructors are never intended to be used (I'm also trying to keep these variables as let types based on Swift's best practices).
In the second case, I'm effectively splitting my constructor into two parts and introduce an additional point of failure in case the second part fails to be called prior to class being used. I also can't move this second part to a method that's guaranteed to be called prior to usage (such as viewDidLoad) because I still need to pass in additional arguments from the config. While I can make sure to call the initPartTwo manually, I'd prefer to have a mechanism that better groups it with the actual constructor. I can't be the first one to run into this and it seems like there is a pattern I'm not seeing to make this cleaner.
UPDATE:
I ended up going with a modified version of the pattern matt suggested:
struct Thing {
let item1: String
let item2: String
struct Config {
let item3: String
let item4: String
}
var config:Config! {
willSet {
if self.config != nil {
fatalError("tried to initialize config twice")
}
}
}
init() {
self.item1 = ...
self.item2 = ...
...
}
public func phaseTwoInit(item3: String, item4: String) {
self.item3 = item3
self.item4 = item4
...
}
}
var t = Thing()
...
t.phaseTwoInit(...)
...
// start using t
If an initial instance variable property value can't be supplied at object initialization time, the usual thing is to declare it as an Optional. That way it doesn't need to be initialized by the class's initializers (it has a value - it is nil automatically), plus your code subsequently can distinguished uninitialized (nil) from initialized (not nil).
If the Optional if an implicitly unwrapped Optional, this arrangement need have no particular effect on your code (i.e. it won't have to be peppered with unwrappings).
If your objection is that you are forced to open the door to multiple settings of this instance variable because now it must be declared with var, then close the door with a setter observer:
struct Thing {
var name:String! {
willSet {
if self.name != nil {
fatalError("tried to set name twice")
}
}
}
}
var t = Thing()
t.name = "Matt" // no problem
t.name = "Rumplestiltskin" // crash

How do you pass statements through an addEventListener?

Iv been trying to pass arguments through an addEventListener event in actionscript such as...
target.addEventListener("pComp", rakeSoil(target));
but i get errors.
Iv tried to google but no luck :/
Thanks for replying if you do :)
The target is already passed as part of the event, either event.currentTarget or event.target will be what you want.
If you want something else passed, create a custom event. Add the property to the custom event.
Try adding an additional method as your event listener:
target.addEventListener ("pComp", targetListener);
...
private function targetListener (event:Event):void {
rakeSoil (event.currentTarget);
}
How this is what you want:
{
var target:EventDispatcher = ...;
Function rakeSoil = function (e:Event):void
{
// handle target
}
target.addEventListener("pComp", rakeSoil);
}
rakeSoil is a first class function(or closure), when event is dispatched, it will be invoked, and you can access 'target' in it.
EDIT:
Have a look at Closure (computer science)
I have always found anonymous functions to be more trouble than they are worth. I would simply follow the standard event handler code layout. It's more formal and takes a little more effort up front, but there is no ambiguity and it is far more readable when you return to it a year from now (reduces head-scratching duration):
// Target extends EventDispatcher
private var target:Target;
public function listenToTarget();
{
target = new Target();
target.addEventListener("pComp", pCompHandler);
}
private function pCompHandler(event:Event):void
{
target.rakeSoil();
}
Although, now that I look at it more closely, why are you having this object do something that Target should be capable of handling internally on its own?

Resources