converting an element of an array to a separate String - arrays

So I have this problem where I can't convert an element of my array to a string
I have a string like this
var description:[String] =["blue","yellow","red"]
and I want to give one element of my array to another variable which is chosen by another integer like this
var pick:[Int] = 2
var chosen:[String] = description[pick]
it says Cannot assign value of type 'String' to type '[String]' and to fix it xcode suggests to do it like this
var chosen:[String] = [description[pick]]
now if I want to cast this variable to another one or give it to a function or whatever it will say Cannot assign value of type 'String' to type '[[String]]' please help.

You are getting very confused here...
First...
var array = ["red", "yellow"]
Is an array of strings. Don't call it description. Call things what they are.
Second...
var pick: [Int]
Is declaring an array. Setting it = 2 doesn't make sense.
Change your last line to...
var chosen: String = array[pick]
In the above line using [String] here is telling the system that you are getting an array of Strings. You're not. You're getting a String here.

Is required for variable chosen to be an array?
Otherwise you could just:
var chosen: String = description[pick]

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]

Finding index to value in [[String]]

Looking for a way to check if an [[String]] array contains a value and then find the index of that value.
The [[String]] array is named: "categoriesArray" and contains three String arrays
Tried using .indexOf like below:
var location = categoriesArray.indexOf(array1)
But I get an error saying:
Cannot convert value of type '[String]' to expected argument type '([String]) throws -> Bool'
Anyone know how I can solve this?
indexOf or it newer version index(where:) takes closure as parameter, not an object you're looking for. Correct usage:
// index will return optional Int
var location = categoriesArray.index(where:{$0==roundLightArray})

Array Name being described as a String

I Have multiple arrays and I want to choose one to be my main array. I want the main Array to be described as a String. How can I name the new array by using my StationID String and my DirectionID String?
let Farbhof1 = ["hi","some","Strings"]
var StationID = "Farbhof"
var DirectionID = "1"
DestViewController.TableViewArray = "\(StationID)\(DirectionID)"
You cannot do that in Swift. Variable names need to be known at compile time, they cannot be calculated at runtime.

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))

Initialize Array to Blank custom type OCAML

ive set up a custom data type
type vector = {a:float;b:float};
and i want to Initialize an array of type vector but containing nothing, just an empty array of length x.
the following
let vecarr = Array.create !max_seq_length {a=0.0;b=0.0}
makes the array init to {a=0;b=0} , and leaving that as blank gives me errors. Is what im trying to do even possible?
You can not have an uninitialized array in OCaml. But look at it this way: you will never have a hard-to-reproduce bug in your program caused by uninitialized values.
If the values you eventually want to place in your array are not available yet, maybe you are creating the array too early? Consider using Array.init to create it at the exact moment the necessary inputs are available, without having to create it earlier and leaving it temporarily uninitialized.
The function Array.init takes in argument a function that it uses to compute the initial value of each cell.
How can you have nothing? When you retrieve an element of the newly-initialized array, you must get something, right? What do you expect to get?
If you want to be able to express the ability of a value to be either invalid or some value of some type, then you could use the option type, whose values are either None, or Some value:
let vecarr : vector option array = Array.create !max_seq_length None
match vecarr.(42) with
None -> doSomething
| Some x -> doSomethingElse
You can initialize and 'a array by using an empty array, i.e., [||]. Executing:
let a = [||];;
evaluates to:
val a : 'a array = [||]
which you can then append to. It has length 0, so you can't set anything, but for academic purposes, this can be helpful.

Resources