Swift Programming Beginner : Why is there an error in my loop when implementing a Variable? - swift

When I try and run my code in Xcode playground I get a warning:
Variable 'n' was never mutated; consider changing to 'let' constant.
First of all, I am changing the variable in the body of the loop so why is it telling me to change it to a let (constant) data type.
func multiples (n : Int) {
var n = 1
for _ in (3 ..< 1000) {
var n = n + 1
let multiple3 = 3 * n
print(multiple3)
}
}

I am changing the variable in the body of the loop
No, you’re not. The one in the body of the loop is a different n.
To fix that, change
var n = n + 1
To
n = n + 1

3 little notes:
a) If you read carefully messages from Xcode, you will understand about vars' lifetime and usage. ("Variable 'n' was never mutated; consider changing to 'let' constant" )
b) you have two var with same name in different scope
c) the you enter "for", n on the left will be computed using N in outer scope, so inner n will always be == 2
d) using debugger You will see as in picture.

Those are two different variables named n. One is unchanged and one is created for each new iteration of the for loop.
The reason you can have two variables with the same name is that they exist in different scopes and the one inside the for loop temporarily overrides the one outside the loop for the duration of the loop but only inside it.

Related

Confused by the `m..n` notation in MiniZinc

I have seen the "dot-dot" notation (..) in different places. In the following example, 0..n tells us the domain of the decision variable (which in this case, are the entries of the array s).
int: n;
array[0..n-1] of var 0..n: s;
Another example would be in the for-loop:
constraint forall(i in 0..sequence_length)(
t[i] = sum(k in 0..sequence_length)((bool2int(t[k] == i)))
);
In fact, we can even do something like
par var 1..5: x
My feeling is that the expression m..n is generally used when we define a variable (instead of a parameter), and we want to specify the domain of the variable. But in the second case, we are not defining any variable. So when do we use m..n? What is it exactly (e.g. does it have a type?)?
m..n denotes the set of (consecutive) integers from m to n. It could also be written explicitly as {m,m+1,m+2,...,n-1,n}.
Using a set as the domain, e.g.
var 0..5: x;
could be written as
var {0,1,2,3,4,5}: x;
or (which is probably a weird style):
var {1,5,2,3,0,4}: x;
but both represents the set 0..5.
When using m..n in a forall(i in m..n) ( .... ) loop it means that i is assigned from m to n.
A set is always ordered as this little model shows:
solve satisfy;
constraint
forall(i in {0,4,3,1,2,5}) (
trace("i: \(i)\n")
)
;
The trace function prints the following, i.e. ordered:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5

Forward reference extends over definition of variable in scala

I have a list. For all the numbers in odd position I want to make it 0. And for all the numbers in even position, I want to keep it as it is.I'm trying to do it via map in the following way.
Here's my code
def main(args: Array[String]) {
var l1 = List (1,2,3,4,5,6)
println(l1.map(f(_)))
var c = 0
def f(n:Int):Int =
{
if (c%2 == 0)
{c +=1
return n}
else
{c += 1
return 0}
I want the variable to keep track of the position. But as it seems,I can't forward reference 'c'.
I get the following error
scala forward reference extends over definition of variable c
I can't also declare 'c' inside the function, because it will never increment that way.
What should be the idea way to achieve what I am trying, with the help of map.
I have a list. For all the numbers in odd position I want to make it
0. And for all the numbers in even position, I want to keep it as it is.
Here's an elegant solution of this problem:
l1.zipWithIndex map { case (v, i) => if (i % 2 == 0) v else 0 }
As for the reason, why your code fails: you're trying to access variable c before its declaration in code. Here:
println(l1.map(f(_)))
var c = 0
Your function f is trying to access variable c, which is not declared yet. Reorder these two lines and it will work. But I'd recommend to stick with my initial approach.

Swift Hoisting? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
As everyone knows, JavaScript "Hoists" the variables to the top of the file or scope. But from my understanding, using let is the same as var only let is confined to the scope it is defined in.
Being a compiled language instead of an interpreted, can we assume Swift does NOT do this?
For example:
x = 10
var y = x + 10
var x
can we assume Swift does NOT do this?
You can assume whatever you want, but no matter the programming language, your absolute best bet it to just try it and find out. If you would have pasted your sample code into a Playground or in any Swift-capable IDE, or just tried running it through the command line, you'd quickly find out that this simply does not work.
Your question is somewhat confusing, but I think I can address all or at least most of your questions.
x = 10
var y = x + 10
var x
Assuming there is no other code to go with your original sample, it simply does not compile. All three lines have a problem.
The first two lines complain about the use of an unresolved identified 'x'. In English, this means Swift can't figure out what variable you're talking about. Variables in Swift must be declared before they are used, so the declaration on line three doesn't help the next two lines.
The third line complains that it can't figure out what type x should be. "Type annotation missing in pattern". In some cases, Swift can figure out what type our variable should be. For example, with var x = 10, Swift can figure out that x's type should be Int. If we want something else, we must specify. But if we aren't assigning a value in the declaration, Swift has no idea and must be told: var x: Int?
What about the case where x exists at a different scope?
Well, Swift allows variable shadowing. That is to say, a variable declared at one scope hides a variable declared at another scope.
So, for example:
class Foo {
let x = 10
func foo(value: Int) -> Int {
let a = value * self.x
let x = 10
return a * x
}
}
Now we can use some x before we've declared a locally scoped x, but these are different variables. Also, perhaps most importantly, notice the self. prepended to x here. It's required. Without it, Swift will refuse to compile this code and will complain: "Use of local variable 'x' before its declaration."
However, within functions of classes is not the only place we can shadow variables. We can also do it within if blocks (among other places) which is where things can get a little more confusing. Consider this:
class Foo {
let x = 10
func foo(value: Int) -> Int {
print(x)
if x > 3 {
let x = 2
print(x)
}
return x
}
}
Here, we've used x twice before declaring it. And we didn't have to make use of the self. and it doesn't complain and compiles perfectly fine. But it's important to note that outside the if block (including the x > 3 conditional) the x we're referencing is the instance variable, but inside the if block, we've created a new variable called x which shadows the instance variable. We can also create the same sort of shadowing by using if let and if var constructs (but not guard let).
The result of calling this function will be that the value 10 is printed, we enter the if block, the value of 2 is printed, then we exit the if block and the value of 10 is returned.
Now let's through var into the mix here. First, if you aren't already aware, you should start by reading this which explains the difference between let and var (one is a constant, the other is not).
Let's combine let vs var with scoping and variable shadowing to see how it effects things.
class Foo {
let x = 10
func foo(value: Int) -> Int {
print(x)
if x > 3 {
var x = 2
while x < 10 {
print(x)
x += 3
}
return x
}
return x
}
}
Okay, so this is the same as before but with a slightly more complicated bit within the if block.
Here, our locally-scoped variable is declared as a var while our instance variable remains a constant let. We cannot modify the instance variable, but we can modify the local variable. And we do so, on each iteration of the while loop.
But importantly, this variable is an entirely different variable from the instance variable. It might as well have a completely different name (and in practice, it basically always should have a different name). So modifying our local variable x doesn't change anything about our more broadly scoped instance variable x. They're different variables that reside in different memory locations. And once a variable is declared as a let or a var, that variable cannot be changed to the other.
'let' and 'var' do not have a difference in scope.
Global variables are variables that are defined outside of any
function, method, closure, or type context. Local variables are
variables that are defined within a function, method, or closure
context.

How does rowfun know to reference variables inside a table

From the documentation, we see the following example:
g = gallery('integerdata',3,[15,1],1);
x = gallery('uniformdata',[15,1],9);
y = gallery('uniformdata',[15,1],2);
A = table(g,x,y)
func = #(x, y) (x - y);
B = rowfun(func,A,...
'GroupingVariable','g',...
'OutputVariableName','MeanDiff')
When the function func is applied to A in rowfun how does it know that there are variables in A called x and y?
EDIT: I feel that my last statement must not be true, as you do not get the same result if you did A = table(g, y, x).
I am still very confused by how rowfun can use a function that does not actually use any variables defined within the calling environment.
Unless you specify the rows (and their order) with the Name/Value argument InputVariables, Matlab will simply take column 1 as first input, column 2 as second input etc, ignoring eventual grouping columns.
Consequently, for better readability and maintainability of your code, I consider it good practice to always specify InputVariables explicitly.

openscad If statement issue with variable

I have a problem with If statement in OpenScad.
I have 4 variables
a=20;
b=14;
w=1;
c=16;
I want to check witch number is bigger a or b.
And after depending who is smaller to take the value of smaller variable(in our case b < a) and to make a simple operation with c variable ( c=b-w).
I tried like this but it doesn't work.
a=20;
b=14;
w=1;
c=16;
if(a>b)
{
c=b-w;
}
if (a<b)
{
c=a-w;
}
if (a==b)
{
c=a-w;
}
It seems logic, but in openscad as I understood you can't change the value of variable inside a If statement. What trick can I use in order to get my goal.
Thank you!
in the 3. leg you confused the assignment-operator „=“ with the equal-operator „==“ (correct if (a==b)).
in your 3. leg you do the same as in the 2., so you could handle both as an „else“-leg.
Correct: assignment is not allowed in if-statement. In openscad you can use the ? operator instead:
c = a > b ? b-w : a-w;
After = follows the condition. The statement after the ? becomes the value if the condition is true, and the statement after the : becomes the value if the condition is false. Nested conditions are possible, e.g. your conditions:
c = a > b ? b-w : (a < b ? a-w : a-w);
More information in the documentation.
OpenSCAD's variable assignment is different. You can only assign variables inside a bracket. So c = b - w will only be assigned inside the if bracket. Outside if this bracket it will still be 16. Don't ask me why. You can read more in the Documentation of OpenSCAD.
c = min(c,min(a,b)/2-w);
this also solve the problem )