Finding index to value in [[String]] - arrays

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

Related

How do I retrieve an item from an array that is inside a dictionary?

I'm trying to create a dictionary that has an array as the value of one of the dictionary items in Swift. I want to be able to retrieve a certain element in the array, but when I try to do it I get an error.
Here's my code:
var country = ["USA": [37.0902, 95.7129]]
let countrylatitude = country["USA"]
print(countrylatitude[0])
The error message was: Value of optional type '[Double]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Double]'
What does this mean? Thanks!
Unwrapped basically means to check and make sure the value exists. countrylatitude possibly could be equal to nil because it doesn't know if "USA" is part of the dictionary.
There are multiple ways to unwrap to make sure it exists...
Force unwrap will crash if it is equal to nil
countrylatitude![0]
if let will only run if it can define a constant that is not equal to nil
if let latitude = countrylatitude {
print(latitude[0])
}
guard let will not run any code after the guard statement unless it is not equal to nil
guard let latitude = countrylatitude else { return }
print(latitude[0])
Keep in mind that if the index of latitude[0] is not automatically assigned optional so if when you do countrylatitude[0] it is essentially just force unwrapping the index and it will crash if that index [0] does not exist.

converting an element of an array to a separate String

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]

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

Scala: Appending to the end of an array which is a value in a HashMap

var temp = 5
val map = new HashMap[String,Array[Integer]]()
if(map contains str1){
map(str1) = map(str1) :+ temp
}else{
map(str1) = Array(temp)
}
Basically if the key is not in the map, I want to set the value to a new array with the value temp and if the key is already in the map I want to append temp to the end of the existing array. temp is an Integer.
I'm getting the following error when I execute the code above:
helloworld.scala:21: error: type mismatch;
found : Array[Any]
required: Array[Integer]
Note: Any >: Integer, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ >: Integer`. (SLS 3.2.10)
map(str1) = (map(str1) :+ temp)
^
I am new scala, so I'm completely lost as to why this is happening. Thanks for any help.
There are two problems with this code. I'm assuming you're using a mutable HashMap first of all, because you'd otherwise not be able to update it.
First, you're getting a compile error because you've declared a HashMap[String, Array[Integer]], but you're trying to append an Int to the Array[Integer]. They are not the same thing. Therefore the compiler infers the type as Any, which isn't allowed because the type parameter of Array is invariant.
So change your declaration to val map = new HashMap[String,Array[Int]](). There's isn't much of a reason to use Integer in scala. And if you really need to then use val temp = new Integer(5), instead.
The second problem that you haven't been able to see yet from the first compiler is that this won't work:
map(str1) = Array(temp)
If the str1 key does not exist on the HashMap, then calling map(str1) will throw an exception, so a new key cannot be assigned this way. Instead, you have to add the key-value pair to the map like this:
map += (str1 -> Array(temp))

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