I've been making a game with the LOVE2D game engine, and I've stumbled across an issue. I want to access a variable inside a nested table, but I don't know how.
Here's my code right now:
local roomNum = 1
local rooms = { r1 = { complete = false, name = "Room 1" }
if rooms[roomNum].complete == true then --problematic line
--do stuff
end
If I replace rooms[roomNum].complete with rooms.r1.complete then it works.
Any help would be appreciated!
'http://lua-users.org/wiki/TablesTutorial'
The provided link gives easy to understand examples on tables in Lua, so it may prove a useful resource in the future.
As for the why the replacement code worked, a dictionary is just sets of key/value pairs (kvp) . In examples from other languages, these pairs are normally shown as something like KeyValuePair.
In your case, you are using a variation on how dictionaries are used. As you have seen, you can use numbered indexes like room[1], or you can use a string like room["kitchen"]. It gets interesting when you provide a set of data to initialize the dictionary.
Building off of the provided data, you have the following:
local rooms = { r1 = { complete = false, name = "Room 1" }
r1 is equivalent to using rooms["r1"] without the dataset. In providing the dataset, any "named" Key can be referenced like it is a property of the dictionary (think of classes with public getter/setter). For the named keys of a dataset, you can provide a key as numbers as well.
local rooms = { [1] = { complete = false, name = "Room 1" }
This indexing fits the direction you were headed on providing a room index. So, you could either swap the dataset to use integers instead of r1, r2 and so on, or you could concatenate r and the index numbering. That is pretty much up to you. Keep in mind as you go further down nesting the same rules apply. So, complete could look like rooms[1].complete, rooms["r1" ].complete, or rooms.r1.complete.
I have an array which has two types of objects: Awarded and non-awarded. I simply want to sort my array so that awarded objects are placed first, and the rest are placed afterwards.
Here is the code that defines the key "awarded":
if let awarded = achievements[indexPath.row].userRelation["awarded"] as? String where awarded != "<null>" { }
Within those brackets I'd like to use my unwrapped value "awarded" to sort through the achievements and add those to the beginning, and the rest at the end.
How would I go about doing that?
You should experiment with sort function, it is very useful.
let sortedAchievements = achievements.sorted{ $0.userRelation["awarded"] < $1.userRelation["awarded"] }
To sort in place use this:
achievements.sort{ $0.userRelation["awarded"] < $1.userRelation["awarded"] }
I would recommend to refactor your model. It's better to use objects or structs instead of dictionaries. Also awarded should be a Bool property, not a String, right?
I have a PFObject subclass which stores an array of strings as one of its properties. I would like to query for all objects of this class where one or more of these strings start with a provided substring.
An example might help:
I have a Person class which stores a firstName and lastName. I would like to submit a PFQuery that searches for Person objects that match on name. Specifically, a person should be be considered a match if if any ‘component’ of either the first or last name start with the provided search term.
For example, the name "Mary Beth Smith-Jones" should be considered a match for beth and bet, but not eth.
To assist with this, I have a beforeSave trigger for the Person class that breaks down the person's first and last names into separate components (and also lowercases them). This means that my "Mary Beth Smith-Jones" record looks like this:
firstName: “Mary Beth”
lastName: “Smith-Jones”
searchTerms: [“mary”, “beth”, “smith”, “jones”]
The closest I can get is to use whereKey:EqualTo which will actually return matches when run against an array:
let query = Person.query()
query?.whereKey(“searchTerms”, equalTo: “beth”)
query?.findObjectsInBackgroundWithBlock({ (places, error) -> Void in
//Mary Beth is retuned successfully
})
However, this only matches on full string equality; query?.whereKey(“searchTerms”, equalTo: “bet”) does not return the record in question.
I suppose I could explode the names and store all possible sequential components as search terms (b,e,t,h,be,et,th,bet,etc,beth, etc) but that is far from scalable.
Any suggestions for pulling these records from Parse? I am open to changing my approach if necessary.
Have you tried whereKey:hasPrefix: for this? I am not sure if this can be used on array values.
https://parse.com/docs/ios/guide#queries-queries-on-string-values
So I stored several elements, namely, an array of String at a particular key in a dictionary that I created. However, I could not find anything, including the apple developer's guide, regarding accessing a particular element in a dictionary's key. Looking at the code below might make more sense.
import UIKit
var dict = Dictionary<Int, Array<String>>()
dict[1] = ["dog", "cat", "fish"]
dict[1]! += ["poop"]
dict[1]!.append("snacks")
print(dict[1]) //"[dog, cat, fish, poop, snack]\n"
So I want to access dog using a 2d like syntax, e.g., dict[1][0]. So I tried things like, dict.keys[1].Array[0], dict.keys.array[0], and dict[1: [0]] in order to access dog. However, none of these work. Anybody have a solution to this problem? Thank you in advance!
Dictionary subscript in Swift returns optional, so you need to unwrap it:
print(dict[1]![0])
I tried to display datas which is in Dictionary format. Below, three attempts are there. First attempt, output order is completely changed. Second attempt, output order is same as input. But, in third attempt, I declared variable as NSDictionary. Exact output I received. Why this changes in Dictionary? Kindly guide me. I searched for Swift's Dictionary tag. But I couldn't found out.
//First Attempt
var dict : Dictionary = ["name1" : "Loy", "name2" : "Roy"]
println(dict)
//output:
[name2: Roy, name1: Loy]
//Second Attempt
var dict : Dictionary = ["name2" : "Loy", "name1" : "Roy"]
println(dict)
//output:
[name2: Loy, name1: Roy]
-----------------------------------------------------------
//Third Attempt With NSDictionary
var dict : NSDictionary = ["name1" : "Loy", "name2" : "Roy"]
println(dict)
//output:
{
name1 = Loy;
name2 = Roy;
}
ANOTHER QUERY: I have used play ground to verify. My screen shot is below:
Here, In NSDictionary, I gave name5 as first, but in right side name2 is displaying, then, in println, it is displaying in ascending order. Why this is happening??
Here, In Dictionary, I gave name5 as first, but in right side name2 is displaying, then, in println, it is displaying, how it is taken on the Dictionary line. Why this is happening??
This is because of the definition of Dictionaries:
Dictionary
A dictionary stores associations between keys of the same type and values of the same type in an collection with no defined ordering.
There is no order, they might come out differently than they were put in. This is comparable to NSSet.
Edit:
NSDictionary
Dictionaries Collect Key-Value Pairs. Rather than simply maintaining an ordered or unordered collection of objects, an NSDictionary stores objects against given keys, which can then be used for retrieval.
There is also no order, however there is sorting on print for debugging purposes.
You can't sort a dictionary but you can sort its keys and loop through them as follow:
let myDictionary = ["name1" : "Loy", "name2" : "Roy", "name3" : "Tim", "name4" : "Steve"] // ["name1": "Loy", "name2": "Roy", "name3": "Tim", "name4": "Steve"]
let sorted = myDictionary.sorted {$0.key < $1.key} // or {$0.value < $1.value} to sort using the dictionary values
print(sorted) // "[(key: "name1", value: "Loy"), (key: "name2", value: "Roy"), (key: "name3", value: "Tim"), (key: "name4", value: "Steve")]\n"
for element in sorted {
print("Key = \(element.key) Value = \(element.value)" )
}
A little late for the party but if you want to maintain the order then use KeyValuePairs, the trade-off here is that if you use KeyValuePairs you lose the capability of maintaining unique elements in your list
var user: KeyValuePairs<String, String> {
return ["FirstName": "NSDumb",
"Address": "some address value here",
"Age":"30"]
}
prints
["FirstName": "NSDumb", "Address": "some address value", "Age": "30"]
Dictionaries, by nature, are not designed to be ordered, meaning that they're not supposed to be (although they can be!).
From the Dictionaries (Swift Standard Library documentation):
A dictionary is a type of hash table, providing fast access to the entries it contains. Each entry in the table is identified using its key, which is a hashable type such as a string or number. You use that key to retrieve the corresponding value, which can be any object. In other languages, similar data types are known as hashes or associated arrays.
This requires some basic knowledge of Data Structures, which I'll outline & oversimplify briefly.
Storing associated data without a dictionary
Consider for a minute if there was no Dictionary and you had to use an array of tuples instead, to store some information about different fruits and their colors, as another answer suggested:
let array = [
("Apple", "Red"),
("Banana", "Yellow"),
// ...
]
If you wanted to find the color of a fruit you'd have to loop through each element and check its value for the fruit, then return the color portion.
Dictionaries optimize their storage using hash functions to store their data using a unique hash that represents the key that is being stored. For swift this means turning our key—in this case a String—into an Int. Swift uses Int-based hashes, which we know because we all read the Hashable protocol documentation and we see that Hashable defines a hashValue property that returns an Int.
Storing associated data with a dictionary
The benefits of using a dictionary are that you get fast read access and fast write access to data; it makes "looking up" associated data easy and quick. Typically O(1) time complexity, although the apple docs don't specify, maybe because it depends on the key type's hash function implementation.
let dictionary = [
"Apple": "Red",
"Banana": "Yellow"
// ...
]
The trade off is that the order is typically not guaranteed to be preserved. Not guaranteed means that you might get lucky and it might be the same order, but it's not intended to be, so don't rely on it.
As an arbitrary example, maybe the string "Banana" gets hashed into the number 0, and "Apple" becomes 4. Since we now have an Int we could, under the hood, represent our dictionary as an array of size 5:
// what things *might* look like under, the hood, not our actual code
// comments represent the array index numbers
let privateArrayImplementationOfDictionary = [
"Yellow", // 0
nil, // 1
nil, // 2
nil, // 3
"Red", // 4
] // count = 5
You'll notice, we've converted our keys into array indices, and there are a bunch of blank spaces where we have nothing. Since we are using an array, we can insert data lightning fast, and retrieve it just as quickly.
Those nil spaces are reserved for more values that may come later, but this is also why when we try to get values out of a dictionary, they might be nil. So when we decide to add more values, something like:
dictionary["Lime"] = "Green" // pretend hashValue: 2
dictionary["Dragonfruit"] = "Pink" // pretend hashValue: 1
Our dictionary, under the hood, may look like this:
// what things *might* look like under, the hood, not our actual code
// comments represent the array index numbers
let privateArrayImplementationOfDictionary = [
"Yellow", // 0 ("Banana")
"Pink", // 1 ("Dragonfruit")
"Green", // 2 ("Lime")
nil, // 3 (unused space)
"Red", // 4 ("Apple")
] // count = 5
As you can see, the values are not stored at all in the order we entered them. In fact, the keys aren't even really there. This is because the hash function has change our keys into something else, a set of Int values that give us valid array indices for our actual storage mechanism, an array, which is hidden from the world.
I'm sure that was more information than you wanted and probably riddled with many inaccuracies, but it gives you the gist of how a dictionary works in practice and hopefully sounds better than, "that's just how it works."
When searching for the actual performance of Swift dictionaries, Is Swift dictionary ... indexed for performance? ... StackOverflow had some extra possible relevant details to offer.
If you're still interested to know more details about this, you can try implementing your own dictionary as an academic exercise. I'd also suggest picking up a book on Data Structures and Algorithms, there are many to choose from, unfortunately I don't have any suggestions for you.
The deeper you get into this topic the more you'll understand why you'll want to use one particular data structure over another.
Hope that helps!
✅ It is possible!
Although the Dictionary is not ordered, you can make it preserve the initial order by using the official OrderedDictionary from the original Swift Repo
The ordered collections currently contain:
Ordered Dictionary (That you are looking for)
Ordered Set
They said it is going to be merged in the Swift's source code soon (reference WWDC21)
Neither NSDictionary nor Swift::Dictionary orders its storage. The difference is that some NSDictionary objects sort their output when printing and Swift::Dictionary does not.
From the documentation of -[NSDictionary description]:
If each key in the dictionary is an NSString object, the entries are
listed in ascending order by key, otherwise the order in which the
entries are listed is undefined. This property is intended to produce
readable output for debugging purposes, not for serializing data.
From The Swift Programming Language:
A dictionary stores associations between keys of the same type and values of the same type in an collection with no defined ordering.
Basically, order of items as seen in output is arbitrary, dependant on internal implementation of data structure, and should not be relied on.
This is indeed an issue with dictionaries. However, there's a library available to make sure the order stays the way you initialised it.
OrderedDictionary is a lightweight implementation of an ordered dictionary data structure in Swift.
The OrderedDictionary structure is an immutable generic collection which combines the features of Dictionary and Array from the Swift standard library. Like Dictionary it stores key-value pairs and maps each key to a value. Like Array it stores those pairs sorted and accessible by a zero-based integer index.
Check it out here:
https://github.com/lukaskubanek/OrderedDictionary