swift3 - Singleton [duplicate] - swift3

This question already has answers here:
Using a dispatch_once singleton model in Swift
(30 answers)
Closed 6 years ago.
How can I convert this to Swift 3:
struct Static {
static var instance : myForm?
static var token : dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = myForm()
}
return Static.instance!

Just this:
static let instance = MyForm()
and call it
let form = MyForm.instance
A note from the documentation:
Stored type properties are lazily initialized on their first access. They are guaranteed to be initialized only once, even when accessed by multiple threads simultaneously, and they do not need to be marked with the lazy modifier.
PS: Consider that struct and class names are supposed to start with a capital letter.

Related

Use parameter in list | Flutter/Dart [duplicate]

This question already has answers here:
Error: The instance member ... can't be accessed in an initializer
(4 answers)
Closed 1 year ago.
I´m new to flutter and got a question that makes me crazy for 2 days :)
I want to use a parameter(name1) in a list, but can´t figure out what went wrong:
List<Widget> player = [Text(name1)];
String name1 = 'Max';
#override
Widget build(BuildContext context) {
return Container(
child: player[0],
);
}
}
Error: Can't access 'this' in a field initializer to read 'name1'
This is a simplified version, but includes the problem.
You cannot use a just initialized variable to initialize another variable. You can call the variable inside a method. For example if is a StatefulWidget, you can fill the list inside the initState method.
List<Widget> player = [];
String name1 = 'Max';
#override
void initState() {
player.add(Text(name1));
super.initState();
}
Or you can initialize the list with all the widgets already:
List<Widget> player = [Text('name1'),Text('name2')];

How do I create a mock function in Rust? [duplicate]

This question already has answers here:
How to mock external dependencies in tests? [duplicate]
(1 answer)
How to mock specific methods but not all of them in Rust?
(2 answers)
How can I test stdin and stdout?
(1 answer)
Is there a way of detecting whether code is being called from tests in Rust?
(1 answer)
What is the proper way to use the `cfg!` macro to choose between multiple implementations?
(1 answer)
Closed 2 years ago.
I'm trying to run unit tests on a function reducer . reducer takes in a struct State and an enum Action and returns a new struct State . When the action is Action::Status , I want the function state.status_function to be called on state. I'm having trouble testing that a mock function I pass into test_status is called with state. Does anyone know what I'm getting wrong in the code below?
fn test_status() {
let mut status_mock_called: bool;
let state = State {
status_function: Box::new(|state: State| {
status_mock_called = true;
return state;
}),
};
assert_eq!(root_reducer(state, Action::Status), state);
assert!(status_mock_called);
}
Outputs the error:
`(dyn std::ops::Fn(State) -> State + 'static)` doesn't implement `std::fmt::Debug`
How can I modify a rust variable from inside a function?
Here is the state struct in case it's relevant:
#[derive(Debug, Eq, PartialEq)]
struct State {
status_function: Box<dyn Fn(State) -> State>,
}
And here is the reducer:
fn root_reducer(state: State, action: Action) -> State {
match action {
Action::Status => (state.status_function)(state),
}
}

How can I verify if I am working with a base or derived object in C++? [duplicate]

This question already has answers here:
Check for derived type (C++)
(6 answers)
Closed 4 years ago.
Let's say I have a class Product and a class AuctionedProduct which derives from Product. I then have a virtual function foo that does 'x' if I'm working with a Product base class and 'y' if it's actually an AuctionedProduct. Given an object, how can I determine which class is actually the one I'm working on?
If you are using inheritance properly, code operating on references of a base class (Product), should not need to know the actual type of the object, but interact with each product the same way.
However, if you really would like to know the actual type, e.g: because of debugging, you can use dynamic_cast:
void f(Product* p)
{
AuctionedProduct* ap = dynamic_cast<AuctionedProduct*>(p);
if (ap) {
// we have an AuctionedProduct
}
else
{
// ap is nullptr, we have a different kind of product
}
}
you can use virtual methods and use different implementation for base class and derived class and use that method for identify object type.
you can find more decription here :
Check for derived type (C++)
Hi you need to use dynamic_cast to find out the object of type like below, dynamic_cast method will return the address of the object if it match with the class type parameter. Also see my comments in the below codes:-
class Product{};
class AuctionedProduct : public Product{};
class NonAuctionedProduct : public Product{};
Product *prod1 = new AuctionedProduct();
Product *prod2 = new NonAuctionedProduct();
AuctionedProduct *ac = NULL;
NonAuctionedProduct *nac = NULL;
ac = dynamic_cast<AuctionedProduct*>(prod1);//here it will return the address as prod1 is a type AuctionedProduct
if(ac != NULL )
{
//ac->dosomething
cout<<"I am class AuctionedProduct<<endl;
}
nac = dynamic_cast<NonAuctionedProduct*>(*prod2);
if(nac != NULL )
{
//nac->dosomething
cout<<"I am class NonAuctionedProduct<<endl;
}
ac = dynamic_cast<AuctionedProduct*>(prod2); //here it will return NULL as prod2 is a object of type NonAuctionedProduct

How to override KeyValuePair<TKey, TValue> in C#?

I want to override the default structure of KeyValuePair in C#, so that I can make a KeyValuePair to accept a 'var' types.
Something like this :
List<KeyValuePair<string, var>> kvpList = new List<KeyValuePair<string, var>>()
{
new KeyValuePair<string, var>("Key1", 000),
new KeyValuePair<string, var>("Key2", "value2"),
new KeyValuePair<string, var>("Key3", 25.45),
};
Even if its possible for dictionary, then also it will solve my problem.
You could use object as your type, and then cast to/from object to desired outcomes. However, it's important to note that this is very much the opposite of object oriented programming, and generally indicates an error in your design and architecture.
Hmm I am wondering if this might help you: To have a list as you want, it is really possible BUT the "var" type (as you named it) must be the same for all KeyValuePair instances. For having whatever type you must use object or dynamic (use Haney's answer).
So considering that you want a single type for all KeyValuePair instances, here is a solution:
Firstly, create this helper class:
public static class KeyValuePairExtentions
{
public static List<KeyValuePair<string, T>> GetNewListOfType<T>(Expression<Func<T>> type)
{
return new List<KeyValuePair<string, T>>();
}
public static void AddNewKeyValuePair<T>(this List<KeyValuePair<string, T>> #this, string key, T element)
{
#this.Add(new KeyValuePair<string, T>(key, element));
}
}
To consume these functions, here is an example:
var lst = KeyValuePairExtentions.GetNewListOfType(() => new {Id = default (int), Name = default (string)});
lst.AddNewKeyValuePair("test1", new {Id = 3, Name = "Keith"});
The ideea is to rely on the powerfull type inference feature that we have in C#.
Some notes:
1) if T is anonymous and you create a new instance of a list in an assembly and consume it in another assembly it is VERY possible that this will NOT work due to the fact that an anonymous type is compiled per assembly (in other words, if you have a variable var x = new { X = 3 } in an assembly and in another var y = new { X = 3 } then x.GetType () != y.GeTType () but in the same assembly types are the same.)
2) If you are wondering whether an instance it's created or not by calling GetNewListOfType, the answer is NO because it is an expression tree function and the function is not even compiled. Even with a Func will work because I am not calling the function in my code. I am using the function just for type inference.

RegExpValidator never matches

I've got a class that's meant to validate input fields to make sure the value is always a decimal. I've tested the regex here: http://livedocs.adobe.com/flex/3/html/help.html?content=validators_7.html, and it looks like it does the right thing, but in my app, I can't seem to get it to match to a number format.
Class Definition:
public class DecimalValidator {
//------------------------------- ATTRIBUTES
public var isDecimalValidator:RegExpValidator;
//------------------------------- CONSTRUCTORS
public function DecimalValidator() {
isDecimalValidator = new RegExpValidator();
isDecimalValidator.expression = "^-?(\d+\.\d*|\.\d+)$";
isDecimalValidator.flags = "g";
isDecimalValidator.required = true;
isDecimalValidator.property = "text";
isDecimalValidator.triggerEvent = FocusEvent.FOCUS_OUT;
isDecimalValidator.noMatchError = "Float Expected";
}
}
Setting the source here:
public function registerDecimalInputValidator(inputBox:TextInput, valArr:Array):void {
// Add Validators
var dValidator:DecimalValidator = new DecimalValidator();
dValidator.isDecimalValidator.source = inputBox;
dValidator.isDecimalValidator.trigger = inputBox;
inputBox.restrict = "[0-9].\\.\\-";
inputBox.maxChars = 10;
valArr.push(dValidator.isDecimalValidator);
}
And Calling it here:
registerDecimalInputValidator(textInput, validatorArr);
Where textInput is an input box created earlier.
Clearly I'm missing something simple yet important, but I'm not entirely sure what! Any help would be much appreciated.
I don't know ActionScript, but as far as I know it's an ECMAScript language, so I expect you need to escape the backslashes if you use a string to define a regex:
isDecimalValidator.expression = "^-?(\\d+\\.\\d*|\\.\\d+)$";
This strikes me as wrong; but I can't quite put my finger on it. For your DecimalValidator instead of composing a RegExpValidator; why not extend it?
public class DecimalValidator extend RegExpValidator{
//------------------------------- CONSTRUCTORS
public function DecimalValidator() {
super()
this.expression = "^-?(\d+\.\d*|\.\d+)$";
this.flags = "g";
this.required = true;
this.property = "text";
this.triggerEvent = FocusEvent.FOCUS_OUT;
this.noMatchError = "Float Expected";
}
}
How when is the registerdecimalInputValidator called? I have a slight worry about the Validator instance is a local variable to a method instead of 'global' property to the function.
protected var dValidator:DecimalValidator = new DecimalValidator();
public function registerDecimalInputValidator(inputBox:TextInput):void {
dValidator.isDecimalValidator.source = inputBox;
dValidator.isDecimalValidator.trigger = inputBox;
}
I'm not sure why you are setting restrictions on the TextInput in the registerDecimalInputValidator method; that should be done when you create the method (in createChildren() or possibly in response to public properties changing, in commitProperties . It is also not obvious to me what the validatorArr does. If you're expecting to access values inside the validatorArrray outside of the method; it would often be a common practice to return that value from the method. Without looking it up; I'm not sure if Arrays are passed by value or reference in Flex.