Differences in for-loops. Swift v.s. Objective-C [duplicate] - objective-c

This question already has answers here:
Removing from array during enumeration in Swift?
(9 answers)
Closed 6 years ago.
In this loop we have the potential to reduce the number of items in the loop while processing it. This code works fine in Obj-C, but the Swift loops don't get the message that an item has been removed and end up overflowing the array.
In Objective-C, we had:
for(int i = 4; i < staticBlocks.count; i++)
{
PlayerSprite* spr = [staticBlocks objectAtIndex:i];
[spr setPosition:CGPointMake(spr.position.x, spr.position.y-1)];
if(spr.position.y < -1000)
{
[staticBlocks removeObject:spr];
[spr removeFromParent];
}
if(spr.blockTypeIndex == Block_Type_Power_Up)
{
[spr update];
}
}
In Swift I know of these options:
//for i in 4.stride(to: staticBlocks.count, by: 1){ //crashes
//for i in 4..<staticBlocks.count{ //crashes
for var i = 4; i < staticBlocks.count; i += 1 { //works, but is deprecated
let spr = staticBlocks.objectAtIndex(i) as! PlayerSprite
spr.position = CGPointMake(spr.position.x, spr.position.y-1)
if(spr.position.y < -1000)
{
staticBlocks.removeObject(spr)
spr.removeFromParent()
//break
}
if(spr.blockTypeIndex == k.BlockType.PowerUp)
{
spr.update()
}
}
In this specific case, it really isn't a problem for me to use a break statement (which is currently commented out) to kill the loop and prevent the crash, but it doesn't seem like the proper fix. I assume there will come a time when I need to know how do do this correctly. Is there a non deprecated way to do a for loop, one which processes the count each pass?
A related, unanswered question.
Is the for loop condition evalutaed each loop in swift?

I don't know how to link to a specific answer, but this code did what I needed. Marking as duplicate now.
Removing from array during enumeration in Swift?
var a = [1,2,3,4,5,6]
for (i,num) in a.enumerate().reverse() {
a.removeAtIndex(i)
}

This is because in Swift you cannot remove items from an array while you are iterating over it.
From this question Removing from array during enumeration in Swift?
you can see that you should be using the filter function instead of using a for loop.
For example, don't do this:
for (index, aString: String) in enumerate(array) {
//Some of the strings...
array.removeAtIndex(index)
}
Do something like this:
var theStrings = ["foo", "bar", "zxy"]
// Filter only strings that begins with "b"
theStrings = theStrings.filter { $0.hasPrefix("b") }
(Code example from this answer)
Additionally, it should be noted that filter won't update the array, it will return a new one. You can set your array to be equal to that array afterwards.
An additional way to solve the issue, from the same question is to do this:
var a = [1,2,3,4,5,6]
for (i,num) in a.enumerate().reverse() {
a.removeAtIndex(i)
}
print(a)

Related

Three different ways to instantiate Arrays in AssemblyScript

I'm writing a smart contract and want to use Arrays to manipulate data, but looking at the AssemblyScript docs, I'm not sure the best way to proceed.
It seems fine to me to just use:
let testData:string[] = []
but when I consulted the assemblyscript docs, there are three recommended ways to create an Array:
// The Array constructor implicitly sets `.length = 10`, leading to an array of
// ten times `null` not matching the value type `string`. So, this will error:
var arr = new Array<string>(10);
// arr.length == 10 -> ERROR
// To account for this, the .create method has been introduced that initializes
// the backing capacity normally but leaves `.length = 0`. So, this will work:
var arr = Array.create<string>(10);
// arr.length == 0 -> OK
// When pushing to the latter array or subsequently inserting elements into it,
// .length will automatically grow just like one would expect, with the backing
// buffer already properly sized (no resize will occur). So, this is fine:
for (let i = 0; i < 10; ++i) arr[i] = "notnull";
// arr.length == 10 -> OK
When would I want to use one type of instantiation over another? Why wouldn't I just always use the version I presented in the beginning?
Nothing wrong with the array literal approach. It is basically equivalent to
let testData = new Array<string>();
However, sometimes you know what the length of the array should be and in such cases, preallocating the memory using Array.create is more efficient.
UPDATE
With this PR Array.create deprecated and should not be used anymore.
OLD ANSWER
let testData:string[] = []
semantically the same as
let testData = new Array<string>()
AssemblyScript doesn't support preallocated sparse arrays (arrays with holes) for reference elements which not explicitly declared as nullable like:
let data = new Array<string>(10);
data[9] = 1; // will be compile error
Instead you could use:
let data = new Array<string | null>(10);
assert(data.length == 10); // ok
assert(data[0] === null); // ok
or Array.create but in this case your length will be zero. Array.create is actually just reserve capacity for backing buffer.
let data = Array.create<string>(10);
assert(data.length == 0); // true
For plain (non-reference) types you could use usual way without care about nullabe or creating array via Array.create:
let data = new Array<i32>(10);
assert(data.length == 10); // ok
assert(data[0] == 0); // ok

Remove an Array element [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So im trying to code a function to remove an element from an Array.for some reason i'm getting no errors but still does not print the result i need. i think the problem is in the function or data type declaration.
#import <Foundation/Foundation.h>
void deleteArray(char stra[ ], char ElementToRemove);
int main(int argc, const char * argv[]) {
#autoreleasepool {
char str[100];
printf("Please Enter Array Elements\n");
scanf("%s",&str);
deleteArray(str, "a");
printf("%s",&str);
}
return 0;
}
void deleteArray(char stra[ ], char ElementToRemove)
{
int NumberOfElements = sizeof(stra);
int ElementPos;
for (int i = 0; i >= NumberOfElements;i++)
{
if (ElementToRemove == stra [i])
{
ElementPos = i;
}
}
for (int SecondCounter = ElementPos; SecondCounter >= NumberOfElements;SecondCounter++ )
{
stra[SecondCounter] = stra[SecondCounter - 1];
}
}
There are many issues with your code, let's see them one by one.
When you pass an array to a function, it decays to a pointer to the first element of the array. So, sizeof in the deleteArray() function is not doing what you think it's doing there.
You can use strlen() instead to get the length of a char array. However, please note, this does not count the terminating null, anyways, and you need to move that one, too, to make the end of the modified array.
Then, in the for loop,
for (int i = 0; i >= NumberOfElements;i++) //false always....
is wrong. I believe what you want is
for (int i = 0; i < NumberOfElements;i++)
After that, regarding the call to the function should be
deleteArray(str, 'a'); // 'a' is a char
instead of
deleteArray(str, "a"); // "a" denotes a string
Next, in the main() function, remove the & from the argument to printf(). It should look like
printf("%s",str);
Also, to ensure safety from buffer overflow, you should make yourscanf() to look like
scanf("%99s",str);
If you need dynamically sized arrays, I recommend making them the last flexible array member (that wikipage has an example) of some (growable) struct and keep the size of that array in its containing struct ....
If you want to have array features, such as add, delete, move and so on, use linked lists. Linked lists are using pointers, so you can represent an array using them. This way it is possible to delete an element, move it or add a new one.
When declaring an array in c, you declare it fixed size. In your case, if you want not to use pointers and lists, you have to copy array elements to a new one, excluding the unneeded.

Is there a way to set restrictions on arc4random()'s results?

I'm making three random choices between two classes, A and B. I need to avoid getting B all three times.
Is there a way to stop arc4random() from giving me that result?
One approach is: If your random routine gives you an unacceptable answer, run it again until it gives you an acceptable answer.
For example, in a solitaire game app of mine, I shuffle a deck and deal some of it into a layout which must be solvable. But what if it isn't solvable? I repeat that: I shuffle the deck again and deal it again. I keep doing that until the layout I've dealt is solvable. All of that happens before the user sees anything, so the user doesn't know what I've been up to behind the scenes to guarantee that the layout makes sense.
In your case, where the possibilities are so limited, another obvious alternative would be this: use a simple combinatorial algorithm to generate beforehand all acceptable combinations of three nodes. Now use arc4random to pick one of those combinations. So, for example:
var list = [[String]]()
let possibilities = ["A","B"]
for x in possibilities {
for y in possibilities {
for z in possibilities {
list.append([x,y,z])
}
}
}
list.removeLast()
Now list is an array of all possible triples of "A" or "B", but without ["B","B","B"]. So now pick an element at random and for each of its letters, if it is "A", use class A, and if it is "B", use class B. (Of course I suppose we could have done this with actual classes or instances, but it seems simplest to encode it as letters.)
BOOLs and loops to the rescue...
BOOL classA = false;
BOOL classB = false;
for (int i=0; i<3; i++) {
int r = arc4random() % 2;
if(i < 2) {
if(r == 0) {
NSLog(#"Class A");
classA = true;
} else {
NSLog(#"Class B");
classB = true;
}
} else {
if(classA == false)
NSLog(#"Class A");
if(classB == false)
NSLog(#"Class B");
}
}
The 2 BOOLs guarantee that each class has at least one member for each 3 cycle run.

Counter as variable in for-in-loops

When normally using a for-in-loop, the counter (in this case number) is a constant in each iteration:
for number in 1...10 {
// do something
}
This means I cannot change number in the loop:
for number in 1...10 {
if number == 5 {
++number
}
}
// doesn't compile, since the prefix operator '++' can't be performed on the constant 'number'
Is there a way to declare number as a variable, without declaring it before the loop, or using a normal for-loop (with initialization, condition and increment)?
To understand why i can’t be mutable involves knowing what for…in is shorthand for. for i in 0..<10 is expanded by the compiler to the following:
var g = (0..<10).generate()
while let i = g.next() {
// use i
}
Every time around the loop, i is a freshly declared variable, the value of unwrapping the next result from calling next on the generator.
Now, that while can be written like this:
while var i = g.next() {
// here you _can_ increment i:
if i == 5 { ++i }
}
but of course, it wouldn’t help – g.next() is still going to generate a 5 next time around the loop. The increment in the body was pointless.
Presumably for this reason, for…in doesn’t support the same var syntax for declaring it’s loop counter – it would be very confusing if you didn’t realize how it worked.
(unlike with where, where you can see what is going on – the var functionality is occasionally useful, similarly to how func f(var i) can be).
If what you want is to skip certain iterations of the loop, your better bet (without resorting to C-style for or while) is to use a generator that skips the relevant values:
// iterate over every other integer
for i in 0.stride(to: 10, by: 2) { print(i) }
// skip a specific number
for i in (0..<10).filter({ $0 != 5 }) { print(i) }
let a = ["one","two","three","four"]
// ok so this one’s a bit convoluted...
let everyOther = a.enumerate().filter { $0.0 % 2 == 0 }.map { $0.1 }.lazy
for s in everyOther {
print(s)
}
The answer is "no", and that's a good thing. Otherwise, a grossly confusing behavior like this would be possible:
for number in 1...10 {
if number == 5 {
// This does not work
number = 5000
}
println(number)
}
Imagine the confusion of someone looking at the number 5000 in the output of a loop that is supposedly bound to a range of 1 though 10, inclusive.
Moreover, what would Swift pick as the next value of 5000? Should it stop? Should it continue to the next number in the range before the assignment? Should it throw an exception on out-of-range assignment? All three choices have some validity to them, so there is no clear winner.
To avoid situations like that, Swift designers made loop variables in range loops immutable.
Update Swift 5
for var i in 0...10 {
print(i)
i+=1
}

Objective C: Using a BOOL to return 'YES' if a condition can be applied

Hi there I have some code at the moment that gives me the error ("0") is not equal to ("50") - condition not applied correctly Basically I am currently using a traditional for loop within a BOOL which goes through the list of items and checks whether or not the condition can be applied, if it can be applied to an item then the BOOL will return YES. I cannot see where I am currently going wrong and need guidance. My code is shown below:
-(BOOL)conditionCanBeApplied:(NSArray *)items{
bool itemConditionCanBeApplied = NO;
for (int i = 0; i < items.count; i++)
{
id myItem = [[items valueForKeyPath:#"itemId"]objectAtIndex: i];
if ([self.applicableItems containsObject:myItem]) {
itemConditionCanBeApplied = YES;
}
}
return itemConditionCanBeApplied;
}
First, don't mix BOOL and bool, they might be very similar but they aren't the same data type. Second, always use fast enumeration if you have a choice. I am assuming in the code below that your items collection is something like an NSArray. Also, there is no reason to test with an if statement just to set a BOOL since the test is a boolean statement. (I am doing it in my example to allow for the break) Lastly, short-circuiting your logic with a break keeps the processor from doing unnecessary work once you have at least one match.
Do something like this:
- (BOOL)conditionTest
{
BOOL itemConditionCanBeApplied = NO;
for (id item in items) {
if ([self.applicableItems containsObject:item]) {
itemConditionCanBeApplied = YES;
break;
}
}
return itemConditionCanBeApplied;
}