Why increment inside function isn't working? - ios

I try to make function run only one time during runtime, but it fires every time instead
var requestCount: Int = 0
func JSONRequest() {
if self.requestCount == 0 {
...some stuff
self.requestCount = requestCount + 1
} else {
println("JSONRequest dismissed")
}
During debugging I figured out that every time JSONRequest() runs it has value of self.requestCount equal to zero. For some reason it doesn't save increment and every time i call the function the self.requestCount is 0.
Why ? What am I doing wrong ?

Could it be that your code is in a ViewController which is being re-created each time (and therefore the count is re-initialized to zero each time)?
If so, you can do one of the following:
use a singleton - not always the cleanest but it works
use persistence (e.g., CoreData or NSUserDefaults)

Related

swift smooth (interpolate) between incoming continuous data

Working in Swift I have a function which is called on arrival of new data (Double between 0 and 1). I need this function to go smoothly to the next value. In another language (MaxMSP) I could simply say go in 20 milliseconds from the previous value to the new one, this would even work if new data arrived before the set time was over. How could I achieve this in Swift? I've found vDSP.convolve() but I'd need an array of values to interpolate between, in my case data is real time and I have the latest value and previous value(s). The code I have is
var previousValue: Double = 0
var value: Double = 0 {
didSet {
valueDidChange()
}
}
private func valueDidChange() {
let valueSmooth = value * //smoothing magic with previousValue
}

Starting countdown in update func

I want to start a countdown after I add a sprite to make sure other sprites will add/ functions will be called after a certain amount of time. So far I have made sure the variable countdownCanStart will change from false to true as I add my sprite.
Inside the touchesBegan function:
//adding the sprite by touch
addSprite()
if spriteAdded {
countdownCanStart = true
}
Then in the update func:
override func update(currentTime: NSTimeInterval) {
if countdownCanStart {
var framecount = 0
framecount++
if framecount == 10 {
AddTheOtherSprites()
}
}
}
The code runs, it doesn't crash, but next to the row AddTheOtherSprites() I see a yellow warning sign: "Will never be executed"
In your update function, you are declaring a fresh variable framecount and initializing it to 0. Then incrementing it, then checking if it’s equal to 10. It never will be - every time you run update, a new framecount variable will be declared and it will only ever be of value 1 when it’s tested against 10 in the if statement.
You're creating framecount within your update method, therefore a new framecount is created every time update begins and destroyed when update ends. Because of this the maximum framecount will ever reach is 1 (from framecount++) and so framecount == 10 always returns false. To solve this, place framecount outside your update method.
This warning is due to framecount being a local scoped var (in regards to the update method) ,so every time the update method will be called framecount will be initialized with 0 and incremented by 1 so it will never be equal to 10.
Change the scope of framecount to be outside the update method

How to reduce NSTimeInterval every time the score is increased by 5

I have a variable called duration which is a NSTimeInterval(3). 3 is the number of objects on the screen and the new object begin to fall when the last is at the bottom of the screen. I want this number reduce, because it will fall faster when there will be less objects. I want it reduce every time the score is increased by 5 from last reduce. But if I write there this code it does nothing:
if ((self.score % 5) == 0) {
self.duration--
}
How can I do it?
Thanks
I guess the "Swifty" answer would be something like this:
var score:Int {
didSet {
self.duration--
}
}
That said you haven't really given enough info to say why self.duration-- would not work, so I'm assuming that code just isn't being called.

Swift: Random number arrays inside images and variables with a for loop

I am creating a game in which, depending on the number of 'swipes' chosen to do, (let's say 3), 3 different patterns show on the screen, one by one. I am working on developing the first pattern.
So I have this:
if (swipes.no_of_swipes) == 3 {
swipeArray = Array<UInt32>(count: 3, repeatedValue: 0)
for i in 0 ..< 3 {
swipeArray[i] = arc4random_uniform(84)}
}
As far as I am aware, this code creates an array with three UInts which can be accessed by doing swipeArray[0], swipeArray[1], and swipeArray[2]. My first question is how long will this swipeArray stay the same? Until the close the view? Should I have a 'refresh button' when the user loses - and if so, how would I make one?
Then I have a property observer. You will notice the for loop, which I am using to keep code concise. I understand that I could do something like x++ somewhere in here so that it will go through each one.
var playBegin: Bool = false{
didSet {
if playBegin == true {
println("\(playBegin)")
var swipes = Menu()
if (swipes.no_of_swipes) == 3 {
for i in 0 ..< 3 {
patternRoom.image = UIImage(named: "pattern\(swipeArray[x])")
//rest of code
}
}
}
The pattern image comes from a set of 84 images named like pattern7 and pattern56. My second question is, how could I code the for loop to go through each swipeArray[x].
Thank you in advance,
Will
how long will this swipeArray stay the same?
This is a bit too open ended. It’ll stay the same until you assign a new value to it, either from this same bit of code or a different part. Only you can know when that will be, by looking at your code.
Since you express an interest in keeping the code concise, here’s a couple of code tips.
You might think about writing your first snippet’s loop like this:
swipeArray = (0..<swipes.no_of_swipes).map { _ in
arc4random_uniform(84)
}
This combines creating a new array and populating the values. By the way, just in case you don’t realize, there’s no guarantee this array won’t contain the same value twice.
It’s also probably better to make swipeArray of type [Int] rather than [UInt32], and to convert the result of arc4random to an Int straight away:
Int(arc4random_uniform(84))
Otherwise the UInt32s will probably be a pain to work with.
For your second for loop, you can do this:
for i in swipeArray {
patternRoom.image = UIImage(named: "pattern\(i)")
// rest of code
}
When writing Swift, usually (but not always), when you find yourself using array[x] there’s a better more expressive way of doing it.

Objective-C and integers outside methods

I have a question regarding integers outside of methods in Objective-C/Xcode. I'm trying to create a simple guessing game, however my randomizer randomize number every time when the method is called, here is the code snipped:
- (IBAction)guessButton:(id)sender {
int tempUserGuess = [self.textField.text integerValue];
int randomNumber = (arc4random() % 11);
if(tempUserGuess == randomNumber){
self.guessAns.text = #"you won!";
}
if (tempUserGuess < randomNumber){
self.guessAns.text = #"no! too low!";
}
if (tempUserGuess > randomNumber){
self.guessAns.text = #"no! too high!";
}
}
The reason why I'm trying to put an int outside of the method is of that once randomized integer should not be randomized every single time (of course). By the way, everything works fine, the app compiles and works but every single time when I hit return, it randomizes the number.
I know how to do this in Java, but Objective-C seems to be more complex.
Your guessButton method is probably a member of some class. You need to add property to that class holding that randomized number.
You only have to create/store a random number once per game play. There is no need to call the randomize method each time the guess button is pressed. The guessButton method is basically like an ActionListener in java. Each time the button is pressed, whatever's inside the curly braces will be executed. If you add a play again button to the game, then you might want to call the randomize method inside of it's action method.
if(tempUserGuess == num){
self.guessAns.text = #"you won!";
}
This will be a good way because it will be using less memory in the sytem when trying to divert the random number. Good work
Okay, I got it.
Here is the answer:
in ViewController.h I had to include:
NSInteger num;
and then in ViewController.m a method that simply returns a number:
-(int)giveRandom {
int randomNumber = (arc4random() % 10);
return randomNumber;
}
And then refer to 'num' in the method with if statements such as:
...
if(tempUserGuess == num){
self.guessAns.text = #"you won!";
}
...
For some reason it returns 0, but I will try to solve it.
Thanks!

Resources