How to declare a Swift Array - arrays

I'm trying to figure out my errors in a swift program it is my first program in swift and I'm learning the syntax. How would one declare an array in swift?

If you wish to declare an array in Swift there are two ways. The most popular and most idiomatic is to use square brackets around a type. For an Array of Ints you might have:
var myArrayOfInts : [Int]
This is syntax sugar for using the generic Array struct so you could equivalently write:
var myArrayOfInts : Array<Int>
Though I don't believe I have ever seen that written in any code (after the square bracket syntax was introduced) in any case that wasn't an example (just like this one) of how the two are equivalent.

You should Try
var temp = [Int]()

Very simple
var myArray: [String] = []

Related

How to show elements of array?

I have a small problem. I created a large array.
It looks like this:
var Array = [
["text10", "text11", ["text01", "text02"]],
["text20", "text21", ["text11", "text12"]]
]
If we write this way: Array[0] that shows all the elements.
If we write this way: Array[0][0] that shows "text1".
If we write this way: Array[0][2] that shows
-2 elements
-- 0: "text01"
-- 1: "text02"
.
If we write this way: Array[0][2].count or Array[0][2][0] it will not work
How do I choose each item, I need these elements for the tableView
The problem basically is that your inner array is illegal. Swift arrays must consist of elements of a single type. You have two types of element, String and Array Of String. Swift tries to compensate but the result is that double indexing can’t work, not least because there is no way to know whether a particular element will have a String or an Array in it.
The solution is to rearchitect completely. If your array entries all consist of the same pattern String plus String plus Array of String, then the pattern tells you what to do; that should be a custom struct, not an array at all.
as #matt already answered but I want to add this thing
Why Array[0][2].count or Array[0][2][0] not work
If you Define array
var array = [
["text10", "text11", ["text01", "text02"]],
["text20", "text21", ["text11", "text12"]]
]
And when you type array you can see it's type is [[Any]] However it contains String as well as Array
So When you try to get Array[0][2] Swift does not know that your array at position 2 has another array which can have count
EDIT
What you are asking now is Array of dictionary I suggest you to go with model i.e create struct or class and use it instead of dictionary
Now If you want to create dictionary then
var arrOfDict = ["text10" : ["text01", "text02"] , "text11" : ["text11", "text12"]]
And you can access with key name let arrayatZero = arrOfDict["text10"] as? [String]

MiniZinc join arrays of variables by index

I have a MiniZinc program with 3 arrays of variables of the following form:
array[NbLines] of var Domain: vars1;
array[NbLines, NbRows] of var Domain: vars2;
array[NbLines, NbRows] of var Domain: vars3;
I need to specify my search variable order in the following way, but I did not success to correctly construct my array. There is the MiniZinc like code:
varsOrder = [[vars1[i]] ++ row(vars2, i) ++ row(vars3, i) | i in NbLines]
MiniZinc indicates that arrays are not allowed in array comprehension expressions. How should I do?
Thank you for your help.
As you have noticed, you cannot concatenate arrays like this. What I can think of are two approaches, though the first is not exactly what you want.
1) use array1d(array)
You can flatten matrices (2d arrays) with "array1d" like this:
solve :: int_search(vars1 ++ array1d(vars2) ++ array1d(vars3), first_fail, indomain_min, complete) satisfy;
However, this is not exactly the same as what you write above, but it's way easier than the next approach:
2) Make a master array and insert all the elements in the proper positions.
int: totLen = ...; % the total length of all the arrays
array[1..totLen] of var Domain: all;
You have to do a loop to insert all the elements in the exact position you want in the "all" array. However, I leave this as an exercise. :-)
Then the "all" array can be used in the labeling:
solve :: int_search(all, first_fail, indomain_min, complete) satisfy;

Creating nested arrays in swift

I'm trying to create nested arrays in Swift of data that's input in the following format:
(+ 5 (- 1 (+ 34 1)))
So the nested array would look like:
[+, 5, [-, 1, [+, 34, 1]]]
with arr[0] always being the operation (+,-,*, or /)
I'm very new to swift and don't really know where to start, so I'd really appreciate the help.
You can put integers, strings, and even functions in the same array by using an enumeration and its associated values. The example does not lend itself to an array but simply a recursive nesting of numbers and computations.
enum Input {
case Operator((Int, Int) -> Int)
case Number(Int)
}
Edit: Per Rob's suggestion.
enum Input {
case Operator((Int, Int) -> Int)
case Number(Int)
indirect case Computation(operator: Input, left: Input, right: Input)
}
This shows how to declare a recursive enumeration. I wish there was a way to limit the operator parameter to Input.Operator and parameters left and right to Input types not .Operator.
you could use array with type of AnyObject as below example.
let arr: [AnyObject] = ["+", 5, ["-", 1, ["/", 34, 1]]]
So in order to get operand you can get at index 0. Let say you want operand division "/" as sample above you can go at this index
arr[2][2][0]
As Price Ringo suggests, a recursive enum is definitely the right tool here. I would build it along these lines:
enum Operator {
case Add
case Subtract
}
enum Expression {
indirect case Operation(Operator, Expression, Expression)
case Value(Int)
}
let expression = Expression.Operation(.Add,
.Value(5),
.Operation(.Subtract,
.Value(1),
.Operation(.Add, .Value(34), .Value(1))))
If you wanted to, you could do it Price's way with functions, and that's probably pretty clever, but I suspect would actually be more of a headache to parse. But if you wanted to, it'd look like this:
enum Expression {
indirect case Operation((Int, Int) -> Int, Expression, Expression)
case Value(Int)
}
let expression = Expression.Operation(+,
.Value(5),
.Operation(-,
.Value(1),
.Operation(+, .Value(34), .Value(1))))
Alternately, you could create an Operator type rather than passing in functions. That's how I'd probably recommend going unless you really want to be able tow
I think you can't build the arrays with different types.. I mean you want to build an Array with Integers and the operators should be Strings... but you can't have both in an array.
check this link, it might be helpful http://totallyswift.com/nested-collections/
Your example looks like a classic Lisp expression. Reflecting that, have you considered the possibility that arrays are a force fit, and you might have an easier time of it with lists as the underlying representation? A list data type would be trivial to implement.

Unexpected error in Array append with Swift

var playerOneArray : Array<(Int,Int,Int)> = []
var currentPerson = 1
var currentWeapon = 1
var currentRoom = 1
var currentPlayer = 1
currentPerson = everyPicker.selectedRowInComponent(0)
currentWeapon = everyPicker.selectedRowInComponent(1)
currentRoom = everyPicker.selectedRowInComponent(2)
currentPlayer = playerPicker.selectedRowInComponent(0)
//In an if statement
playerOneArray.append(currentRoom, currentPerson, currentWeapon) as (Int,Int,Int)
// Error tuple types () and (Int,Int,Int) have a different number of elements (0 vs. 3)
even if i take away the as int,int,int there is still an error and i don't know why this is happening. the error that comes up if i take it away is accessing members of protocol 'int' is unimplemented.
You are not closing the parenthesis of the append call.
However, because swift knows playerOneArray is an array of 3 Ints. You can simply pass the append method the 3 variables as follows:
playerOneArray.append(currentRoom, currentPerson, currentWeapon)
Assuming (currentRoom, currentPerson, currentWeapon) is a tuple of Int values. This will store (currentRoom, currentPerson, currentWeapon) into playerOneArray[0].
As a side note, it seems you are wanting an array of players which holds each players details. If this is the case you should rename the playerOneArray to players and simply add each player's information. That way each index will represent the players information (the tuple of Ints).
You've got the right idea but your syntax is incorrect.
The way it's written, Swift is looking for a method with the signature:
func append(Int, Int, Int) -> (Int, Int, Int)
That is, a function named append that takes three Ints and returns a tuple of three Ints. The error you're getting is probably because Swift sees the definition append(T) -> () and is complaining that you return 3 components rather than zero.
You could try to just pass a tuple by adding parenthesis but this would fail because Swift treats a single tuple as a list of parameters so it looks for a signature append(Int, Int, Int) -> () which does not exist:
playerOneArray.append((currentRoom, currentPerson, currentWeapon)) // Missing argument for parameter #2 in call.
The correct solution looks very close to what you were doing (maybe you were hinted in that direction):
playerOneArray.append((currentRoom, currentPerson, currentWeapon) as (Int,Int,Int))
This tells Swift that you mean that tuple to really be a tuple and it successfully finds the signature: append((Int, Int, Int)) -> ().
As a side note, tuples are intended for transferring data more so than storing it. If you expect this data to persist long term you should put it in a struct:
struct Player {
var person:Int
var weapon:Int
var room:Int
}
var playerOneArray:[Player] = []
let player = Player(
person: everyPicker.selectedRowInComponent(0),
weapon: everyPicker.selectedRowInComponent(1),
room: everyPicker.selectedRowInComponent(2))
playerOneArray.append(player)
append is getting three parameters instead of one tuple. Try this:
playerOneArray.append((currentRoom, currentPerson, currentWeapon))

create dynamic size array swift

I want to create an Array, if i make it like this it works:
var arrayEingabe = Array(count:30, repeatedValue:0)
If i make it like this it does not work:
var sizeArray = 30
var arrayEingabe = Array(count:sizeArray, repeatedValue:0)
At the end i want to change the size of my Array depending on what the user typed in.
I was searching the web for one hour now, but i could not find the answer.
Thanks for your help guys
Greets
Kove
Actually both your examples compiled OK for me, but you should be more specific about types. Something like:
var arrayCount:Int = 30
var arrayEingabe = Array(count:arrayCount, repeatedValue:Int())
actually this might be better for you:
var arrayEingabe = [Int]()
This creates an empty array, and as mentioned in the comments Swift arrays are mutable. You can add, replace and delete members as you want.
On Swift 3.0.2 :-
Use Array initializer method give below:-
override init(){
let array = Array(repeating:-1, count:6)
}
Here, repeating :- a default value for Array.
count :- array count.

Resources