I have spent some time trying to search for this and I haven't found a solution. I am trying to access a specific array value in a dictionary. Below is the general code/explanation for what I want to do.
var dict = ["1": [1,2,3,4,5], "2": [6,7,8,9,10], "3": [11,12,13,14,15]]
//now lets say I want to access the 3rd value of dict["2"] = 8
//I have tried the following and failed
print(dict["2": [2]])
print(dict["2"][2])
Thanks
Here is the way you can achieve that:
var dict = ["1": [1,2,3,4,5], "2": [6,7,8,9,10], "3": [11,12,13,14,15]]
let temp = dict["2"]![2] // 8
Related
Here's what I would like to do.
number = [ 0, 1, 2]
array0 = [ "AA", "BB"]
array1 = [ "CC", "DD"]
array2 = [ "EE", "FF"]
I want to be able to be able to reference the name of the array by doing something like this.
selectedArray = "array" + String(number[2])
then with this, I would like to be able to reference the values inside such as
print("array2:\(selectedArray[1]))
/// The answer would be --> array2:FF
Right now, I've not been able to achieve this, and I tried this but it doesn't work.
selectedArray = Array("array" + String(number[2]))
I tried googling but not knowing how to describe this, I didn't fare well in the results.
Note : The array is a list of GPS Dist / Lat / Lon (very long) and rather than have 1 very huge array, I'm thinking of splitting them out into eg: 10 diff arrays
Not sure I understand correctly what you are trying to achieve and the logic but you can create an array of arrays (lat and long). Something like this:
let number = [0,1,2] // not sure why you need this array
let array = [[ "AA", "BB"],
[ "CC", "DD"],
[ "EE", "FF"]]
let selectedNumber = number[2]
print("array\(selectedNumber):\(array[selectedNumber][1])")
However, I would advice to use this approach:
create a Model for you Coordinates
struct Coordinates {
var lat:String //this should be a Double but
//for the sake of the example I use String
var long:String //Same here
}
then in the controller add data to an array of Coordinates
let coordinate1 = Coordinates(lat: "AA", long: "BB")
let coordinate2 = Coordinates(lat: "CC", long: "DD")
let coordinate3 = Coordinates(lat: "EE", long: "FF")
let array2:[Coordinates] = [coordinate1,coordinate2,coordinate3]
let selectedNumber = number[2]
print("array\(selectedNumber):\(array2[selectedNumber].long)")
which still prints
array2:FF
I am just started to learn Swift and am new to ios development too.
var bookArray:[String:[[String:String]]] = ["book1":[["bookid":"SCIENCE","viewed":"12"],["bookid":"MATHS","viewed":"25"]],"book2":[["bookid":"HISTORY","viewed":"10"]]]
I will get the input as outer dictionary key and inner dictionary key, need to check and update dictionaries.
(i.e)
If the given outer dictionary key is "book1" and inner dictionary key is "MATHS" then the required output to be
bookArray:[String:[[String:String]]] = ["book1":[["bookid":"SCIENCE","viewed":"12"],["bookid":"MATHS","viewed":"26"]],"book2":[["bookid":"HISTORY","viewed":"10"]]]
(viewed count to be incremented)
If the given outer dictionary key is "book1" and inner dictionary key is "CHEMISTRY" then the required output to be
bookArray:[String:[[String:String]]] = ["book1":[["bookid":"SCIENCE","viewed":"12"],["bookid":"MATHS","viewed":"25"],["bookid":"CHEMISTRY","viewed":"0"]],"book2":[["bookid":"HISTORY","viewed":"10"]]]
(New Bookid to be added for the given outer key with viewed count as zero)
I started to work, but there was lot of complications with for loop and too many confusions...
Can some one suggest me some better way to accomplish the result?
Maybe the following code can help you get it to the final answer.
var myDict : [String:[[String: String]]] = [:]
myDict = ["book1": [["bookid":"SCIENCE","viewed":"12"], ["bookid":"MATHS","viewed":"25"]], "book2":[["bookid":"HISTORY","viewed": "10"]]]
func updateKey(_ outKey: String, _ innerKey: String){
var array = myDict[outKey] ?? []
if let index = array.firstIndex(where: {$0["bookid"] == innerKey}){
array[index]["viewed"] = "\(Int(array[index]["viewed"]!)! + 1)"
}
else {
array += [["bookid":innerKey,"viewed":"0"]]
}
myDict[outKey] = array
}
updateKey("book1", "MATHS")
print(myDict)
// ["book2": [["viewed": "10", "bookid": "HISTORY"]], "book1": [["viewed": "12", "bookid": "SCIENCE"], ["viewed": "26", "bookid": "MATHS"]]]
updateKey("book1", "CHEMISTRY")
print(myDict)
//["book2": [["viewed": "10", "bookid": "HISTORY"]], "book1": [["viewed": "12", "bookid": "SCIENCE"], ["viewed": "26", "bookid": "MATHS"], ["viewed": "0", "bookid": "CHEMISTRY"]]]
I would suggest creating a struct for Book
struct Book {
let bookID: String
let viewed: Int
}
and holding an array of that. Will be easier to manage.
Your array will change to:
var bookArray: [String:Book] = [Book(bookID: "SCIENCE", viewed: 12)]
You can create more books and add them to the array
If I have the following array and I want to create a string array containing the door prizes by mapping the mysteryDoors array as keys for the dictionary, and get the corresponding values into a new array.
Thus I would get a string array of ["Gift Card", "Car", "Vacation"] how can I do that?
let mysteryDoors = [3,1,2]
let doorPrizes = [
1:"Car", 2: "Vacation", 3: "Gift card"]
You can map() each array element to the corresponding value in
the dictionary. If it is guaranteed that all array elements are
present as keys in the dictionary then you can do:
let mysteryDoors = [3, 1, 2]
let doorPrizes = [ 1:"Car", 2: "Vacation", 3: "Gift card"]
let prizes = mysteryDoors.map { doorPrizes[$0]! }
print(prizes) // ["Gift card", "Car", "Vacation"]
To avoid a runtime crash if a key is not present, use
let prizes = mysteryDoors.flatMap { doorPrizes[$0] }
to ignore unknown keys, or
let prizes = mysteryDoors.map { doorPrizes[$0] ?? "" }
to map unknown keys to a default string.
If you have to use map, then it would look something like the following:
let array = mysteryDoors.map { doorPrizes[$0] }
After re-reading the Apple Doc example code and changing it to what I need. I believe this is it (Almost). Unfortunately it is now in string format with new lines...
let myPrizes = doorPrizes.map { (number) -> String in
var output = ""
output = mysteryDoors[number]!
return output;
}
I want to implement a multiple click in my Shinobi DataGrid. I have a grid which have array
( ["1", "32", and more] )
If I click the grid I put it into new Array self.arrayNr.append(currNr).
But I want to check and remove if currNr is already exist in arrayNr it is will be remove from the arrayNr.
I'm new and using Swift 3. I read some question regarding with my question like this and this but it's not working. I think the Swift 2 is simpler than Swift 3 in handling for String. Any sugesstion or answer will help for me?
You can use index(of to check if the currNrexists in your array. (The class must conform to the Equatable protocol)
var arrayNr = ["1", "32", "100"]
let currNr = "32"
// Check to remove the existing element
if let index = arrayNr.index(of: currNr) {
arrayNr.remove(at: index)
}
arrayNr.append(currNr)
Say you have an array of string, namely type [String]. Now you want to remove a string if it exists. So you simply need to filter the array by this one line of code
stringArray= stringArray.filter(){$0 != "theValueThatYouDontWant"}
For example, you have array like this and you want to remove "1"
let array = ["1", "32"]
Simply call
array = array.filter(){$0 != "1"}
Long Solution
sampleArray iterates over itself and removes the value you are looking for if it exists before exiting the loop.
var sampleArray = ["Hello", "World", "1", "Again", "5"]
let valueToCheck = "World"
for (index, value) in sampleArray.enumerated() {
if value == valueToCheck && sampleArray.contains(valueToCheck) {
sampleArray.remove(at: index)
break
}
}
print(sampleArray) // Returns ["Hello", "1", "Again", "5"]
Short Solution
sampleArray returns an array of all values that are not equal to the value you are checking.
var sampleArray = ["Hello", "World", "1", "Again", "5"]
let valueToCheck = "World"
sampleArray = sampleArray.filter { $0 != valueToCheck }
print(sampleArray) // Returns ["Hello", "1", "Again", "5"]
I created an array that contains different numbers and each time the button is clicked the array advances to the next index number.
var currentNumber = 0
var random = ["1", "2", "3", "4", "5", "6"]
#IBAction func numberUp(sender: UIButton)
numberLabel.text = random[currentNumber]
++currentNumber
I tried to get similar results in with Parse but i couldn't. I created a class with a array in it
var numbers = PFObject(className:"Numbers")
numbers["number"] = ["1","2","3","4","5","6"]
numbers.save()
How would i go about doing the same thing but with the array i created on Parse. Or how could i retrieve the array from Parse and assign it to a local array ?
First you have to create a PFQuery like
let query = PFQuery(className: "Numbers")
Create a query to download the data in the table:
let result = query.find()
Then assume you have only one row in the table:
let arrayOfNumbers = result.first
Then you can iterate on arrayOfNumbers