Immediately-called closures in Swift [closed] - closures

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Does anyone know how to create an immediately-called closure in Swift? I tried my hand at it but I don't think the feature is supported:
// Playground - noun: a place where people can play
import Cocoa
var initialize: () = { () -> () in
var str = "Hello World"
struct Example {
var myString: String
}
}()
println("Hello")
println(str)
Example(myString: "Hello World")
I get the following errors:
Use of unresolved identifier 'str'
Use of unresolved identifier 'Example'
EDIT:
::FACEPALM:: I just realized this is working as expected: anything outside of the scope of that initialize function isn't available to the program, naturally. :P

The closure is being called immediately but the definitions within the braces are lost when the scope of the closure is exited. This works:
var str = "before"
var initialize: () = { () -> () in
str = "Hello World"
}()
println(str)

You are trying to access str that is declared within the scope of the closure, outside of its scope. That will never work.
Also, please note that you are not actually capturing the closure in the initialize variable. In swift, the assignment of variables does not return anything (as indicated by the ()). The only exception to that is in the case of if let and if var
So you can create an immediately called closure but you cannot capture it in a variable.

Related

Dart type tests work differently between local variable and class member variables [duplicate]

This question already has an answer here:
Smart cast (automatic type promotion) using 'is' is not working
(1 answer)
Closed 2 years ago.
I am working with dart without allowing implicit dynamics and casts and I noticed the following:
When working with a local variable, I can use a type check on that variable and if the test passes, the compiler will just assume that I can use that variable as that type:
var emp; // set to something
if (emp is Person) {
// The compiler infers that emp is a person within this scope
// so it allows me to use Person's member functions and variables
// without the need for explicit typecast
// https://dart.dev/guides/language/language-tour#type-test-operators
emp.firstName = 'Bob';
}
However, this does not work if the variable is the member variable of an object:
class SuperPerson {
Object _emp;
/* Various things that could be doing things with _emp here */
void memberFun() {
if (_emp is Person) {
_emp.firstName = 'Bob'; // ERROR: The setter firstName is not defined for type Object.
(_emp as Person).firstName = 'Bob'; // workaround but would like to avoid casts that could fail.
}
}
}
Why is that and how can I overcome it?
Could it be because of potentially other threads changing the value of _emp in between the test and the use?
Edit: I had forgotten that I had already answered this question. See that one instead.
(Since this answer had already been accepted at the time of this edit, I cannot delete it.)

Parameter passing in Swift [duplicate]

This question already has answers here:
When are argument labels required in Swift?
(6 answers)
Closed 6 years ago.
I have the following piece of code written in swift:
func hai(greeting: String, times: Int) -> String {
return "You are greeted + \(greeting) + \(times) times "
}
hai ("Hello", times: 3)
When I call the function hai, if I call it the following way hai("hello", 3) it throws an error and forces me to call the way it was mentioned above.
Can someone please explain why this should be the case? Thanks, I am new to IOS programming.
Each function parameter in Swift has two names - an internal and an external one. When you define function signature the way you did, the external parameter name of times is the same as its internal name. You can tell Swift that you do not want an external name by placing _ in the external name position:
func hai(greeting: String, _ times: Int) -> String
// ^
Learn more about internal/external parameter names in the Swift 2.2 Programming Language Guide.

The contextual keyword 'var' may only appear within a local variable declaration Or In Script Code [duplicate]

This question already has answers here:
Why can't class fields be var? [duplicate]
(4 answers)
Closed 6 years ago.
Hey I'm trying to Define a mock database . I'm encountering an error while trying to equate var to Mock<'Repository'> The error is :
The contextual keyword 'var' may only appear within a local variable declaration Or In Script Code.
The Code that I have written is :
public class MockingDatabse
{
//Mock a Payment Info
var newPayment = new Mock<IPayment>();
}
I know that I can replace 'var' with 'Mock<"Repository">'. But I wanna know I'm not able to use
'var'
Try this:
public class MockingDatabse
{
//Mock a Payment Info
Mock<IPayment> newPayment = new Mock<IPayment>();
}

How in Dart get command line arguments outside of the `main` method? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In C# langauge exists global system variable for this purpose.
Environment.CommandLine
This property provides access to the program name and any arguments specified on the command line when the current process was started.
Dart is asynchronous langauge. It allows self starting processes.
void main() {
task("foo", callback1);
task("baz", callback2);
}
Package tasks.
void task(String name, action()) {
schedule();
addTask(name. action);
}
void schedule() {
// Here we start timer if it not started.
// This timer will get cmd line arguments
// And executes task specified in cmd line arguments
}
P.S.
An official answer from Dart Team: "Not planned".
I cannot understand: "Why this is possible in other platforms through their libraries but in Dart platform this is not possible?".
Why only through "main" parameters which even not ensures that other isolates not substitute these arguments on the surrogate parameters that are not a real OS process command line arguments)?
Here examples:
Go language
func main() {
fmt.Println(len(os.Args), os.Args)
}
Rust language
fn main() {
let args = os::args();
println!("The first argument is {}", args[1]);
}
C# language
class Sample {
public static void Main() {
Console.WriteLine();
String[] arguments = Environment.GetCommandLineArgs();
Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", arguments));
}
}
Ruby language
ARGV.each do|a|
puts "Argument: #{a}"
end
Python language
import sys
print(sys.argv)
PHP language
foreach($argv as $value)
{
echo "$value\n";
}
Node.js language
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});
P.S.
Again, I am convinced that that Dart platform is not like everyone else.
This is only my opinion. It does not change anything.
Thanks, Günter Zöchbauer, for your concern, but do not need to edit this.
If you want to use command-line arguments outside main you have to pass it around. If you want, you can use a global for that.
This behavior is similar to Java, C and C++ (which you forgot to mention).
One big advantage of this approach is, that it is now easy to launch other programs by simply importing them (as a library) and invoking their main. It also makes argument handling more consistent with respect to isolates.

Dart calling a member function by function name [duplicate]

This question already has answers here:
Dynamic class method invocation in Dart
(3 answers)
Closed 8 years ago.
I am wondering if there is anyway to call a function by its name in dart as in javascript.
I would like to do something as such:
foo["bar"]();
I don't want readers to think what the questioner wants isn't possible in Dart, so I'm adding an answer.
You need to use Mirrors to call a method if you have its name available as a string. Here is an example:
import 'dart:mirrors';
class Foo {
bar() => "bar";
}
void main() {
var foo = new Foo();
var mirror = reflect(foo);
print(mirror.invoke(#bar, []).reflectee); // Prints 'bar'.
}

Resources