Why does Swift 2.2 not support fixed sized arrays, maybe swift 3.0 support? - ios

I'm trying to create a game for iPhone (it's simple, just to sharpen my skills), and I've noticed that Apple has yet to show any support for fixed sized arrays (i had a huge issue with keeping track of my enemies I'm spawning and it would have helped a lot to have a fixed array). Does anyone know why they're not supported? Or if they will be supported in Swift 3.0?

You are not writing C, don't carry the C's baggage with you. Arrays in Swift falls into 2 types: constant array, which is fixed-length and fixed value, you can't modify anything; or variable-length and variable value. Each array knows its length (arr.count), so you don't need a separate variable to keep track of it.
As for for loop, the more I write Swift, the less I used this:
for var i = 0; i < arr.count; i++ { ... }
And the more I used these:
for item in arr { ... }
for (index, item) in arr.enumerate() { ... }
arr.forEach { ... }
arr.map { ... }

Related

zig structs, pointers, field access

I was trying to implement vector algebra with generic algorithms and ended up playing with iterators. I have found two examples of not obvious and unexpected behaviour:
if I have pointer p to a struct (instance) with field fi, I can access the field as simply as p.fi (rather than p.*.fi)
if I have a "member" function fun(this: *Self) (where Self = #This()) and an instance s of the struct, I can call the function as simply as s.fun() (rather than (&s).fun())
My questions are:
is it documented (or in any way mentioned) somewhere? I've looked through both language reference and guide from ziglearn.org and didn't find anything
what is it that we observe in these examples? syntactic sugar for two particular cases or are there more general rules from which such behavior can be deduced?
are there more examples of weird pointers' behaviour?
For 1 and 2, you are correct. In Zig the dot works for both struct values and struct pointers transparently. Similarly, namespaced functions also do the right thing when invoked.
The only other similar behavior that I can think of is [] syntax used on arrays. You can use both directly on an array value and an array pointer interchangeably. This is somewhat equivalent to how the dot operates on structs.
const std = #import("std");
pub fn main() !void {
const arr = [_]u8{1,2,3};
const foo = &arr;
std.debug.print("{}", .{arr[2]});
std.debug.print("{}", .{foo[2]});
}
AFAIK these are the only three instances of this behavior. In all other cases if something asks for a pointer you have to explicitly provide it. Even when you pass an array to a function that accepts a slice, you will have to take the array's pointer explicitly.
The authoritative source of information is the language reference but checking it quickly, it doesn't seem to have a dedicated paragraph. Maybe there's some example that I missed though.
https://ziglang.org/documentation/0.8.0/
I first learned this syntax by going through the ziglings course, which is linked to on ziglang.org.
in exercise 43 (https://github.com/ratfactor/ziglings/blob/main/exercises/043_pointers5.zig)
// Note that you don't need to dereference the "pv" pointer to access
// the struct's fields:
//
// YES: pv.x
// NO: pv.*.x
//
// We can write functions that take pointer arguments:
//
// fn foo(v: *Vertex) void {
// v.x += 2;
// v.y += 3;
// v.z += 7;
// }
//
// And pass references to them:
//
// foo(&v1);
The ziglings course goes quite in-depth on a few language topics, so it's definitely work checking out if you're interested.
With regards to other syntax: as the previous answer mentioned, you don't need to dereference array pointers. I'm not sure about anything else (I thought function pointers worked the same, but I just ran some tests and they do not.)

Swift - compare words and filtering

i just started learning Swift and trying to make an assignment for iOS.
what i have is 4 categories of keywords, for example:
CategoryX: hello, bye, good, bad
CategoryY: rain, sun
CategoryZ: sun, hello, what, rain
CategoryV: yes, no, bad, music, song, note
what i want is to compare this categories with each other and the result will give me the keywords that are in the choosen categories.
for example if i choose to compare all the categories, the results will be: null
(because there is no keyword that appear in all categories)
but if i choose X and Z, then the result will be: hello
if Y and Z then its: sun, rain
I’m not asking from anyone to write me the code (but ofc would be nice if someone gave me a headstart), i just want little explanation of how to deal with this problem and what to use to do it the right way, can someone shed some light?
thank you
I’m not asking from anyone to write me the code (but ofc would be nice if someone gave me a headstart), i just want little explanation of how to deal with this problem and what to use to do it the right way, can someone shed some light?
Okay, without giving the answer away, here’s a hint about how to deal with the problem., to give you a head start.
Doesn't this assignment make you think about sets? Remember those Venn diagrams you had to make in high school? Remember the idea of the intersection of sets? Think about that. Think about sets. Hmmm... Swift has a Set struct...
If you follow up that idea, and research what a Set is in Swift, you’ll see what to do.
Had fun writing it so I post it here. If you aren’t finished by now then look at the result and learn from it(my motto).
I expect you to learn .forEach, .map, .filter, guard let and optional subscript, since you skipped the easy answer with Sets. Oh don’t forget closures and how they strongly capture.
func compare(dicts: [[String]]) -> [String] {
var result = [String: Int]()
dicts.forEach { arg0 in
guard let priorResult = result[arg0.key] else {
result[arg0.key] = arg0.value
return
}
result[arg0.key] = priorResult + arg0.value
}
return result.filter{ arg0 in return arg0.value == dicts.count }.map{ return $0.key }
}
.map, forEach and .filter call for every item in the collection(for every key-value pair in a dictionary) thegiven closure.
.map returns an array of what is returned inside map.
.filter returns an array of items for which the closure returned true and so filtering out the items for which the closure returned false.
.forEach is an alternative to a for-loop.
result counts every occurance of a string.
.filter returns true for the strings which occured inside every dict.
.map maps the dictionary’s keys to a simple [String] array.
You can try
let set1 = Set(["123","456","789"])
let set2 = Set(["123","456"])
let set3 = Set(["123"])
let res12 = set1.intersection(set2) // ["123","456"]
let res123 = set1.intersection(set2).intersection(set3) // ["123"]

Swift, How to make an Array of UIBezierPaths?

I can make 1 just fine, and in Objective-C I would just slap a "[10]" on my first declaration and be good to go. But swift arrays are so foreign to me, I don't understand at all. I need a 10x10 grid of squares (UIBezierPaths) Iv tried looking at many posts but I can't understand. Could someone please help out and explain the nature of swift arrays, am I missing something?
thank you
Does this help?
var paths: [[UIBezierPath]] = [[UIBezierPath]]()
for index in 0 ... 9 {
paths.append([UIBezierPath]())
for kdx in 0 ... 19 {
paths[index].append(UIBezierPath())
}
}
Creates a 2d array of UIBezierPath and then iterates over two loops. In the first loop we add a new list of paths and in the second loop we add new paths to these lists.
For a single list of paths just use the inner loop.
var paths: [UIBezierPath] = [UIBezierPath]()
for kdx in 0 ... 9 {
paths.append(UIBezierPath())
}

C-style for statement is deprecated and will be removed in a future

Anyone came across this?
I ve got a nice little loop but it seems to get a warning.
for(;;nimages++)
It was proposed and accepted to remove the ++ and -- operators from the Swift language in an upcoming release, therefore the warning you're seeing is to help you avoid these types of constructs in your code before it is removed. (Please reference the link for a full explanation as well as the advantages and disadvantages that they provide.)
Please note that C-Style loops will also be deprecated in the near future according to the following proposal: https://github.com/apple/swift-evolution/blob/master/proposals/0007-remove-c-style-for-loops.md
Not knowing exactly what kind of logic you need to implement I don't feel confident recommending a solution, however in accordance with the above proposals I would recommend that you may want to become familiar with the Swift for-in and stride statements. Or, as another person recommended, using a while loop may also be appropriate.
What's the question? The entire error message is
C-style for statement is deprecated and will be removed in a future version of
Swift
You could replace this with something like
while true {
// loop body
nimages += 1
}
Finally, if you know the number of iterations you want, you can use a for-in loop:
for nimages in 0..<maxImages { /* loop body */ }
C Style For loops are deprecated and incrementing decrementing like these i++ , i-- also deprecated
Therefore couldn't be used this type of loops anymore
let myArray = ["one","two","three","four","five","six"]
for var i = 0; i < myArray.count; i++ {
print(myArray[i])
}
Instead of use above syntax, we can use this
let myArray = ["one","two","three","four","five","six"]
for i in 0..<myArray.count {
print(myArray[i])
}
And also this
for i in 0...myArray.count-1 {
print(myArray[i])
}
If you are not familiar with Range Operators and Half-Open Range Operators this is the time
(Document Link)
Range Operators
The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.
Half-Open Range Operators
The half-open range operator (a..<b) defines a range that runs from a to b, but does not include b.
For index-- style
for index in 10.stride(to: 0, by: -1) {
print(index)//This is 10, 9, 8, ... 1 NOT 0
}
For index++ style
for index in 0..<10 {
}

Is it possible to create a mixed array in vala?

In Vala I see that when I declare an array I have to specify the type, like
int[] myarray = { 1, 2, 3 };
I wonder if there is a way to have a mixed array like
smtg[] myarray = { 1, 'two', 3 };
I see that in this question they say that in C++ and C# it's not possible but I just started learning vala and I have no background with any C-like language so I want to be sure.
No.
That said, you can create an array of something that can hold other types, like GLib.Value or GLib.Variant, and Vala can automatically convert to/from those two, so you could do something like
GLib.Value[] values = {
1,
"two",
3.0
}
It's usually a terrible idea (you're basically throwing away compile time type safety), but you can do it.

Resources