variable is not an instance variable - reason

I made this factorial solver but all it outputs is:
We've found a bug for you!
6| let factorialNumber = 0;
7| Js.log(factorial(factorialNumber));
(error here)8| factorialNumber = factorialNumber + 1;
9|}
The value factorialNumber is not an instance variable
The code
let rec factorial = (n) =>
n <= 0
? 1
: n * factorial(n - 1);
while (true){
factorialNumber = 0
Js.log(factorial(factorialNumber));
factorialNumber = factorialNumber + 1
}

In Reason, variables are immutable by default. You're also not declaring factorialNumber as a variable anywhere.
The changes needed to make this compile is:
Declare the variable using let
Make the variable a mutable reference using ref
Access the value of the reference using ^
Assign a new value to the reference using :=
while (true) {
let factorialNumber = ref(0);
Js.log(factorial(factorialNumber^));
factorialNumber := factorialNumber^ + 1
}
This still doesn't make much sense, however, as you're still just running factorial(0) on every iteration. I suspect what you want is to move the declaration and initial assignment outside the loop, so that it's incremented by one on each iteration:
let factorialNumber = ref(0);
while (true) {
Js.log(factorial(factorialNumber^));
factorialNumber := factorialNumber^ + 1
}

Related

How to assign value after increment Swift?

var str = ["Franc": 2]
var a = 1
str["Franc"] = a += 1
print(str)
When I try this code i get an error on line "str["Franc"] = a += 1" that is "Cannot assign value of type '()' to type 'Int?'"
How to solve this. I need it in single line
Thank you in advance
We can do this directly only in Objective C:
In Objective C:
[str setValue:[NSNumber numberWithInt:a+=1] forKey:#"Franc"];
In Swift
str["Franc"] = a
a += 1
You can increment number like this
str["Franc"]! = a ; a += 1
assign value
var str = ["Franc": 2]
str["Franc"]! += 1
and now str["Franc"] will returns 3
And if you want to avoid force unwrapping
str["Franc"] = (str["Franc"] ?? 0) + 1
Also you can do it using if let
if let num = str["Franc"] as? Double {
str["Franc"] = num + 1
}
I don't think you can do this in a single line:
var str = ["Franc": 2]
var a = 1
str["Franc"] = a
a += 1
print(str)

Int() doesn't convert from String to Optional Integer (Swift)

I'm new at programming and started with Swift. The first issue I came along with is the following:
I have 4 variables
var a = "345"
var b = "30.6"
var c = "74hf2"
var d = "5"
I need to count the sum of Integers (if not integer, it will turn to nil)
if Int(a) != nil {
var aNum = Int(ar)!
}
if Int (b) != nil {
var bNum = Int (b)!
}
and so on..
As far as I understand, the Int() should convert each element into an Optional Integer.
Then I should use forced unwrapping by convertin the Int? to Int and only then I can use it for my purposes. But instead, when I count the sum of my variables, the compiler sums them as Strings.
var sum = aNum + bNum + cNum + dNum
Output:
34530.674hf25
Why my variables, which are declared as strings and then converted into optional integers with Int(), didn't work?
Your code has typos that make it hard to tell what you are actually trying to do:
Assuming your 2nd variable should be b, as below:
var a = "345"
var b = "30.6"
var c = "74hf2"
var d = "5"
///Then you can use code like this:
var sum = 0
if let aVal = Int(a) { sum += aVal }
if let bVal = Int(b) { sum += bVal }
if let cVal = Int(c) { sum += cVal }
if let dVal = Int(d) { sum += dVal }
print(sum)
That prints 350 since only 345 and 5 are valid Int values.

I cant set 2 variables to - each other and equal a third variable in swift

I cant set 2 variables to - each other and equal a third variable in swift
I'm trying to make var1 - var2 == var3 work in swift but I get Result of operator '==' is unused when I use ==
and when I use = I get Cannot assign to value: binary operator returns immutable value this is the code I'm working on.
var pices1 = 1
var pices2 = 1
var warmup: Int = 60
var nexx: Int = 60
func logic() {
if count < 10 {
warmup = 5
count - warmup == nexx
pices1 = 1
pices2 = 1
}
}
== is for checking if two values are equal. = is for assigning a new value to a variable.
Just like when you define a new variable, the destination is on the left and the new value is on the right.
var warmup: Int = 60
In your case, you'll want the following.
nexx = count - warmup

for loop over odd numbers in swift

I am trying to solve the task
Using a standard for-in loop add all odd numbers less than or equal to 100 to the oddNumbers array
I tried the following:
var oddNumbers = [Int]()
var numbt = 0
for newNumt in 0..<100 {
var newNumt = numbt + 1; numbt += 2; oddNumbers.append(newNumt)
}
print(oddNumbers)
This results in:
1,3,5,7,9,...199
My question is: Why does it print numbers above 100 although I specify the range between 0 and <100?
You're doing a mistake:
for newNumt in 0..<100 {
var newNumt = numbt + 1; numbt += 2; oddNumbers.append(newNumt)
}
The variable newNumt defined inside the loop does not affect the variable newNumt declared in the for statement. So the for loop prints out the first 100 odd numbers, not the odd numbers between 0 and 100.
If you need to use a for loop:
var odds = [Int]()
for number in 0...100 where number % 2 == 1 {
odds.append(number)
}
Alternatively:
let odds = (0...100).filter { $0 % 2 == 1 }
will filter the odd numbers from an array with items from 0 to 100. For an even better implementation use the stride operator:
let odds = Array(stride(from: 1, to: 100, by: 2))
If you want all the odd numbers between 0 and 100 you can write
let oddNums = (0...100).filter { $0 % 2 == 1 }
or
let oddNums = Array(stride(from: 1, to: 100, by: 2))
Why does it print numbers above 100 although I specify the range between 0 and <100?
Look again at your code:
for newNumt in 0..<100 {
var newNumt = numbt + 1; numbt += 2; oddNumbers.append(newNumt)
}
The newNumt used inside the loop is different from the loop variable; the var newNumt declares a new variable whose scope is the body of the loop, so it gets created and destroyed each time through the loop. Meanwhile, numbt is declared outside the loop, so it keeps being incremented by 2 each time through the loop.
I see that this is an old question, but none of the answers specifically address looping over odd numbers, so I'll add another. The stride() function that Luca Angeletti pointed to is the right way to go, but you can use it directly in a for loop like this:
for oddNumber in stride(from:1, to:100, by:2) {
// your code here
}
stride(from:,to:,by:) creates a list of any strideable type up to but not including the from: parameter, in increments of the by: parameter, so in this case oddNumber starts at 1 and includes 3, 5, 7, 9...99. If you want to include the upper limit, there's a stride(from:,through:,by:) form where the through: parameter is included.
If you want all the odd numbers between 0 and 100 you can write
for i in 1...100 {
if i % 2 == 1 {
continue
}
print(i - 1)
}
For Swift 4.2
extension Collection {
func everyOther(_ body: (Element) -> Void) {
let start = self.startIndex
let end = self.endIndex
var iter = start
while iter != end {
body(self[iter])
let next = index(after: iter)
if next == end { break }
iter = index(after: next)
}
}
}
And then you can use it like this:
class OddsEvent: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
(1...900000).everyOther{ print($0) } //Even
(0...100000).everyOther{ print($0) } //Odds
}
}
This is more efficient than:
let oddNums = (0...100).filter { $0 % 2 == 1 } or
let oddNums = Array(stride(from: 1, to: 100, by: 2))
because supports larger Collections
Source: https://developer.apple.com/videos/play/wwdc2018/229/

Two variables in for loop using Swift

How to use two variables in for loop?
for j,k in zip(range(x,0,-1),range(y,-1,-1)
I want to implement this in Swift.
If your range is a python function, then the Swift-y solution will be:
let x = 100
let y = 99
let rx = reverse(0...x)
let ry = reverse(-1...y)
for (j,k) in zip(rx, ry) {
println(j, k)
}
if you're looping over a dictionary you can loop like this
for (key,value) in dictionary {
}
if an array etc. you're going to have to use a c style for loop
just sub in whatever start and end indices you need
for var j = 0 , k = 0; j < 10 && k < 10; j++ , k++ {
}
EDIT
missed the zip in there. You can loop like this
for (j,k) in zip(range1, range2) {
}