Static function variables in Swift - function

I'm trying to figure out how to declare a static variable scoped only locally to a function in Swift.
In C, this might look something like this:
int foo() {
static int timesCalled = 0;
++timesCalled;
return timesCalled;
}
In Objective-C, it's basically the same:
- (NSInteger)foo {
static NSInteger timesCalled = 0;
++timesCalled;
return timesCalled;
}
But I can't seem to do anything like this in Swift. I've tried declaring the variable in the following ways:
static var timesCalledA = 0
var static timesCalledB = 0
var timesCalledC: static Int = 0
var timesCalledD: Int static = 0
But these all result in errors.
The first complains "Static properties may only be declared on a type".
The second complains "Expected declaration" (where static is) and "Expected pattern" (where timesCalledB is)
The third complains "Consecutive statements on a line must be separated by ';'" (in the space between the colon and static) and "Expected Type" (where static is)
The fourth complains "Consecutive statements on a line must be separated by ';'" (in the space between Int and static) and "Expected declaration" (under the equals sign)

I don't think Swift supports static variable without having it attached to a class/struct. Try declaring a private struct with static variable.
func foo() -> Int {
struct Holder {
static var timesCalled = 0
}
Holder.timesCalled += 1
return Holder.timesCalled
}
7> foo()
$R0: Int = 1
8> foo()
$R1: Int = 2
9> foo()
$R2: Int = 3

Another solution
func makeIncrementerClosure() -> () -> Int {
var timesCalled = 0
func incrementer() -> Int {
timesCalled += 1
return timesCalled
}
return incrementer
}
let foo = makeIncrementerClosure()
foo() // returns 1
foo() // returns 2

Swift 1.2 with Xcode 6.3 now supports static as expected. From the Xcode 6.3 beta release notes:
“static” methods and properties are now allowed in classes (as an
alias for “class final”). You are now allowed to declare static stored
properties in classes, which have global storage and are lazily
initialized on first access (like global variables). Protocols now
declare type requirements as “static” requirements instead of
declaring them as “class” requirements. (17198298)
It appears that functions cannot contain static declarations (as asked in question). Instead, the declaration must be done at the class level.
Simple example showing a static property incremented inside a class (aka static) function, although a class function is not required:
class StaticThing
{
static var timesCalled = 0
class func doSomething()
{
timesCalled++
println(timesCalled)
}
}
StaticThing.doSomething()
StaticThing.doSomething()
StaticThing.doSomething()
Output:
1
2
3

Another solution
class Myclass {
static var timesCalled = 0
func foo() -> Int {
Myclass.timesCalled += 1
return Myclass.timesCalled
}
}

Related

Trying to use if function in Kotlin class

I don´t know why it doesn´t work..
I cant use if or when functions in class or in the "playerPosition" function..
class Player(val name:String, val nachname: String, val nr:Int) {
var position = mutableListOf<Int>(0,1,2,3)
var playerPosi = Int
fun playerPosition(){
if(playerPosi < 3 ){
}
}
}
And the next question is, how can I use a function from a class in the main func.?
Maybe like this
class Player(val name:String, val nachname: String, val nr:Int, var playerPosi : Int) {
var position = mutableListOf<Int>(0,1,2,3)
fun playerPosition(){
if(playerPosi > 3 ){
println("Diese Position gibt es nicht")
}
}
}
MAIN FUNCTION
fun main(){
val team2 = mutableListOf<Player>()
team2.add(Player("Berkan", "Kutlu", 10,4))
val spieler = Player("Wesley","Sneijder",10,4)
playerPosition()
println("${team2.first().playerPosi}")
}
notice
Im trying to set the max Int from playerPosi to 3. Because of Offense, Middfield and Defense and Keeper
If Ive the numbers from 0 to 3 I will try to identify 0 as Keeper 1 as Defense and so on.
Thanks for you patience with me :D
First question
The problem here is not the if keyword, it's because the property playerPosi is wrong.
Instead of writing :
var playerPosi = Int
you need to write :
var playerPosi: Int
Why ?
In kotlin, you have two way to declare a variable / property :
var : mutable variable / property, you can change it's value
val : read-only variable (check Tenfour04 response)
After the var / val keyword you give it a name
And after that you have three choices :
Directly give a value and kotlin will infer the type
var playerPosi = 1
Give it a type and initialize it latter
var playerPosi: Int
Give it a type and initialize it
var playerPosi: Int = 1
Second Question
If you want to call a method of an object (here it's Player), you need to :
Instantiate it
Get the reference
Call the method from the reference
So, if we take your sample :
val team2 = mutableListOf<Player>()
team2.add(Player("Berkan", "Kutlu", 10,4))
val spieler = Player("Wesley","Sneijder",10,4) // Instantiate + take the reference on spieler variable.
speiler.playerPosition() // here you call the playerPosition method with the speiler variable
println("${team2.first().playerPosi}")
Try changing from var playerPosi = Int to var playerPosi: Int, with : instead of =. If you want to define the data type, you should use :; = is used to assign value.
To use the function on object you have previously created, you should first specify the object you want the function to be called into, then a dot, and then the function's name. Like this:
fun main(){
val spieler = Player("Wesley","Sneijder",10,4)
spieler.playerPosition()
}
In the first case: var playerPosi = Int is wrong syntax. Declaration should be var playerPosi: Int.
In the second case: if player is object of class Player, the you can do player.playerPosi.
main() function seems to be written for variant #2, where playerPosi is also constructor parameter.

Dart - declare function as variable

In Dart - as in many other languages - there is more than one way to declare a function. The question is, are there any differences aka "when should I use which"?
void foo(int i) {
print('i = $i');
}
void main() {
void Function(int) bar = (int j) {
print('j = $j');
};
foo(1);
bar(2);
}
Is there any difference in the declaration of foo or bar other than the fact that bar can be overwritten?
Functions can be introduced by
function declarations
method decla-rations
getter declarations
setter declarations
constructor declarations
function literals
In terms of Dart specification there is 2 differences between function literals (aka anonymous function) and other declarations
it has no name - anonymous
we can't declare a return type (which only obtained by means of type inference)
If you prefer to keep type safety, you will have to write long declaration.
Consider this example:
String foo(int i, {bool b}) => '$b $i'; // return type declared
final bar = (int i, {bool b}) => '$b $i'; // return type could not be infered
final String Function(int i, {bool b}) bar = (i, {b}) => '$b $i'; // return type infered
From my perspective
bar isn't as readable as foo declaration
Let functions literals do their anonymous job =)
PS If I missed anything - please edit my answer or reach me in comments

How can I solve 'Duplicate Constructor' error in Haxe?

In Haxe, I created a class named MyClass like:
class MyClass {
var score: String;
public function new (score: Int) {
this.score = Std.string(score);
}
public function new (score: String) {
this.score = score;
}
}
I need multiple constructors but Haxe does not allow me to do. It throws this error from building phase:
*.hx:*: lines * : Duplicate constructor
The terminal process terminated with exit code: 1
How can I solve this problem?
This is known as method overloading, which is not supported by Haxe apart from externs (but might be in the future). There's multiple ways you could work around this.
A common workaround in the case of constructors would be to have a static "factory method" for the second constructor:
class MyClass {
var score:String;
public function new(score:String) {
this.score = score;
}
public static function fromInt(score:Int):MyClass {
return new MyClass(Std.string(score));
}
}
You could also have a single constructor that accepts both kinds of arguments:
class MyClass {
var score:String;
public function new(score:haxe.extern.EitherType<String, Int>) {
// technically there's no need for an if-else in this particular case, since there's
// no harm in calling `Std.string()` on something that's already a string
if (Std.is(score, String)) {
this.score = score;
} else {
this.score = Std.string(score);
}
}
}
However, I wouldn't recommend this approach, haxe.extern.EitherType is essentially Dynamic under the hood, which is bad for type safety and performance. Also, EitherType is technically only intended to be used on externs.
A more type-safe, but also slightly more verbose option would be haxe.ds.Either<String, Int>. Here you'd have to explicitly call the enum constructors: new MyClass(Left("100")) / new MyClass(Right(100)), and then use pattern matching to extract the value.
An abstract type that supports implicit conversions from String and Int might also be an option:
class Test {
static function main() {
var s1:Score = "100";
var s2:Score = 100;
}
}
abstract Score(String) from String {
#:from static function fromInt(i:Int):Score {
return Std.string(i);
}
}
Finally, there's also an experimental library that adds overloading support with macros, but I'm not sure if it supports constructors.
I recommend to use type parameter
class MyClass<T> {
var score:String;
public function new(score:T) {
this.score = Std.string(score);
}
}
You can also use type parameter at constructor
class MyClass {
var score:String;
public function new<T>(score:T) {
this.score = Std.string(score);
}
}
However, T used at constructor fails at runtime (CS and Java), it is not fixed yet (Haxe 4). Otherwise, you could do this
class MyClass {
var score:String;
#:generic public function new<#:const T>(score:T) {
this.score = Std.is(T, String) ? untyped score : Std.string(score);
}
}
which nicely produce code like this (CS)
__hx_this.score = ( (( T is string )) ? (score) : (global::Std.#string(score)) );
causing Std.string() to be called only if T is not a String.
Hej,
With a simple example as it is, you can just do something like that function new( ?s : String, ?n : Int ){} and Haxe will use the correct argument by type. But you'll be able to do new() and maybe you don't want.

How to initialize c++/cx class with aggregate initialization?

I have this ref class:
namespace N
{
public ref class S sealed
{
public:
property Platform::String^ x;
};
}
How do I initialize it in place with the aggregate initializer?
I have tried:
N::S s1 = { %Platform::String(L"text") };
but the compiler says
error C2440: 'initializing': cannot convert from 'initializer list' to
'N::S'
Also:
N::S s1 { %Platform::String(L"text") };
and the error is:
error C2664: 'N::S::S(const N::S %)': cannot convert argument 1 from
'Platform::String ^' to 'const N::S %'
This works greatly with the standard c++ like this:
struct T
{
wstring x;
};
T x { L"test" };
I do not want to use a constructor here.
I assume you mean you don't want a public constructor on the projected WinRT type -- no problem, you can use the internal keyword to mean "public inside C++ but not exposed through interop". That means you can even use native C++ types for your parameters if you like:
namespace Testing
{
public ref class MyTest sealed
{
public:
property String^ Foo {
String^ get() { return m_foo; }
void set(String^ value) { m_foo = value; }
}
internal:
// Would not compile if it was public, since wchar_t* isn't valid
MyTest(const wchar_t* value) { m_foo = ref new String(value); }
private:
String^ m_foo;
};
}
MainPage::MainPage()
{
// Projected type does NOT have this constructor
Testing::MyTest t{ L"Hello" };
OutputDebugString(t.Foo->Data());
t.Foo = "\nChanged";
OutputDebugString(t.Foo->Data());
}
Also you don't need to have the private variable to hold the string -- you could just use the auto-property as in your original code -- but I prefer to be explicit. It also means that if you needed to access the string a lot from within your C++ code you could provide an internal accessor function and not have to go through a vtable call to get at it.

how to pass argument to Marionette.CompositeView

how to pass a values dynamically to an Marionette.CompositeView during run time? like in java we create a method like the following
package com.test.poc;
public class SampleMethod {
public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
SampleMethod method = new SampleMethod();
int firstValue = 90, secondValue = 90;
System.out.println("add : " + method.add(firstValue, secondValue));
}
}
the above is the simple java code anybody can understand like the above how to create and pass arguments to Marionette.CompositeView and work on them?
Best Regards
at the moment you instanciate a view, you can pass whatever arguments you want. normally you pass the model and the collection to be rendered in the compositeView, but you can pass more data if you need.
var MyCompositeView = Backbone.Mationette.CompositeView.extend({
initialize : function (options){
this.dataValue = options.dataValue1;
this.helperObject = options.helperObject;
this.useValues();
},
useValues: function () {
console.log(this.dataValue);
}
});
var helperObject = {
value3 : "I have a value",
value4 : "I dont!"
}; /// a js object literal
var myModel = new MyModel();
var myCollection = new MyCollection();
var myCompositeView = new MyCompositeView({model:myModel,
collection:myCollection,
helperObject:helperObject,
dataValue1:"Hi there"});
notice that Im passing 4 values in the at the time to intanciate the view, and Im reading just two of them, the model and the collection will be handled by marionette, but the other two you can read them in your initialize function.
hope that helps.