I am not expert in Swift and I have been using it for few months to build Mac Apps. I would like to represent in memory a data structure like that of PHP associative arrays but in Swift. Let's imagine that I have a table of data to load in memory with the following fields/records:
ID Surname Name
1 XXX YYY
2 ZZZ WWW
3 JJJ KKK
What I would like to obtain is an associative array like the one I would be able to obtain in PHP:
$arr[1]["Surname"] = "XXX"
$arr[1]["Name"] = "YYY"
$arr[2]["Surname"] = "ZZZ"
$arr[2]["Name"] = "WWW"
I just cannot find the right data structure in Swift to obtain the same result. I tried with the following piece of code:
class resObject: NSObject {
private var cvs = [Int: [String: String]]()
override init() {
self.cvs[0] = ["Name" : "XXX"]
self.cvs[0] = ["Surname" : "YYY"]
self.cvs[1] = ["Name" : "ZZZ"]
self.cvs[1] = ["Surname" : "WWW"]
for (key, arr) in cvs {
let sur = arr["Surname"]
let nam = arr["Name"]
println("Row \(key) - Surname: \(sur), Name: \(nam)")
}
super.init()
}
}
It looks to me pretty close, but it does not work. What I get in the output is the following (I don't care about the "Optional(s)":
Row 0 - Surname: Optional("XXX"), Name: nil
Row 1 - Surname: Optional("ZZZ"), Name: nil
I tried to make some tests in debug and I noticed that the data that are saved in memory are just that of the last key:value pair used (i.e. if I assign Surname first and Name second I get Surname as nil and Name with the correct value).
Please consider that, as in the example, I don't know the data structure when I declare the variable, so I declare it empty and fill it programmatically later.
I don't know if it is just me not declaring the data structure correctly, or if it is Swift that does not allow to do that. Any help will be greatly appreciated.
Thanks a lot.
Regards,
Alessio
One way is a Dictionary of structs. Consider:
struct Person {
var firstName: String
var lastName: String
}
var peopleByID = [ Int: Person ]()
peopleByID[1] = Person(firstName: "First", lastName: "Last")
peopleByID[27] = Person(firstName: "Another", lastName: "LastName")
var myID = 1 // Try changing this to 2 later
if let p = peopleByID[myID] {
println("Found: \(p.firstName) with ID: \(myID)")
}
else {
println("No one found with ID: \(myID)")
}
You can then update the structure:
peopleByID[1].firstName = "XXX"
peopleByID[27].lastName = "ZZZ"
You can iterate freely:
for p in peopleByID.keys {
println("Key: \(p) value: \(peopleByID[p]!.firstName)")
}
Note that a mere array of [Person] isn't so hot, because the IDs:
-- may not be Ints, but are often Strings
-- even if they remain Ints, an array takes up storage in proportion to the highest numbered index, whereas a Dictionary only takes up storage in proportion to the number of stored objects. Imagine storing just two ID's: 523123, and 2467411.
EDIT
It seems like you don't know the attributes ahead of time that will go into each Person object. That's odd, but you should then do:
struct Person {
var attributes = [String : String]() // A dictionary of String keys and String values
}
var peopleByID = [ Int : Person ]()
// and then:
var p1 = Person()
var p2 = Person()
p1.attributes["Surname"] = "Somename"
p1.attributes["Name"] = "Firstname"
p2.attributes["Address"] = "123 Main St."
peopleByID[1] = p1
peopleByID[2] = p2
if let person1 = peopleByID[1] {
println(person1.attributes["Surname"]!)
for attrKey in person1.attributes.keys {
println("Key: \(attrKey) value: \(person1.attributes[attrKey]!)")
}
}
Related
I'm trying to create an array of structs (User structs below) where, if the user.name does not yet exist in the array, it appends the user -- but if the user.name is already present ("Mcdonalds" in the below example), then it will simply add the item.amount to the existing struct.
In other words, the below code should create an array of 4 Users, with the User Mcdonalds item.amount totaling 23.44 + 12.33.
I remember doing this sort of thing in JS no sweat, but I can't for the life of me figure out how to do this in Swift. Thanks for any help!
struct User {
var name: String
var amount: Double
}
var user1 = User(name: "Mcdonalds", amount: 23.44)
var user2 = User(name: "Wendys", amount: 15.44)
var user3 = User(name: "Cabanos", amount: 12.22)
var user4 = User(name: "Shell Gas", amount: 23.33)
var user5 = User(name: "Mcdonalds", amount: 12.33)
To loop over the users they'll need to be in an array to start.
Then you can use .reduce(into:) to reduce them into one condensed dictionary (the dictionary will allow you to have a unique key (the name of the user here) so that you don't have duplicate entries). Then you can use .map() to just get the value and not the key of that dictionary so that the final result will be an array of users.
struct User {
var name: String
var amount: Double
}
var users = [
User(name: "Mcdonalds", amount: 23.44),
User(name: "Wendys", amount: 15.44),
User(name: "Cabanos", amount: 12.22),
User(name: "Shell Gas", amount: 23.33),
User(name: "Mcdonalds", amount: 12.33)
]
var reducedUsers = users.reduce(into: [String: User]()) { (result, nextUser) in
if let existing = result[nextUser.name] {
result[nextUser.name] = User(name: nextUser.name, amount: existing.amount + nextUser.amount)
} else {
result[nextUser.name] = nextUser
}
}.map { $0.value }
A clean and swifty way is to write an extension for Array. Swift is highly protocol-oriented, which means you are able to extend any existing system or self-written class with new functions.
This is just a simple implementation, which uses a function to append or update any given user object:
extension Array where Element == User {
/// Appends a not existing user to the array or updates the amount value if user is already present
mutating func appendOrUpdate(_ userObject: Element) {
// Check if user is already in the array
if let index = self.firstIndex(where: { $0.name == userObject.name }) {
// Update the amount
self[index].amount += userObject.amount
}
else {
// Append the user
self.append(userObject)
}
}
}
As the where clause specifies the extension the Element of the array only to be applied when the given object is your User struct, it is only available when you pass in an user object.
Usage:
var userArray: [User] = []
userArray.appenOrUpdate(User(name: "Mcdonalds", amount: 23.44))
userArray.appenOrUpdate(User(name: "Wendys", amount: 15.44))
userArray.appenOrUpdate(User(name: "Cabanos", amount: 12.22))
userArray.appenOrUpdate(User(name: "Shell Gas", amount: 23.33))
userArray.appenOrUpdate(User(name: "Mcdonalds", amount: 12.33))
This will result in an array with just four entries and the double entry 'Mcdonalds' user's amount cumulated.
Note that the function has the mutating keyword in front, as if not you will not be able to modify the array and its entries. This is necessary due the nature of arrays being Structs themselves.
You can also write a function like the know Array's append(contentsOf:) and pass in an array of user objects and loop through them updating or appending the given objects.
Best way is to put this extension in a separate file called Array+User.swift according to best practise naming conventions.
You can read more about extensions in Swift and their power here: https://docs.swift.org/swift-book/LanguageGuide/Extensions.html
Matthew Gray's answer is very good, and can be used for a wide variety of problems that may be more complex than this one. But for this specific problem, it can be done much more simply.
let reducedUsers = users.reduce(into: [:]) { (result, user) in
result[user.name, default: 0] += user.amount
}
.map(User.init)
The point of this is that it tears apart the struct into key and value in a Dictionary, and then reassembles the values into an Array at the end. Swift is smart enough to figure out the type of the [:], so there's no need to specify that.
Note that there is a time-space tradeoff here. This creates a temporary Dictionary that can be very large. If this kind of operation is common and the dataset is large, you should consider storing this data in a Dictionary ([String: User] or [String: Double]) all the time rather than converting back and forth.
I get an unexpected result when I append a new object onto an array of objects. The append seems to overwrite the existing object in the array then append itself.
Any thoughts? Or am I missing something really simple.
Here's test code from my playground:
class myRecord {
var firstName: String?
var lastName: String?
}
var myRecords = [myRecord]()
var tempRecord = myRecord()
tempRecord.firstName = "John"
tempRecord.lastName = "Brown"
myRecords.append(tempRecord)
tempRecord.firstName = "Jane"
tempRecord.lastName = "Doe"
myRecords.append(tempRecord)
for x in 0..<myRecords.count {
print(x, "=", myRecords[x].firstName!, myRecords[x].lastName!) }
Console output:
0 = Jane Doe
1 = Jane Doe
This happens obviously because class are Reference Type. if your creating object of class that means your are creating memory reference of that class. And if you are changes property of that class that means your are changing the value of that reference in your memory heap. That why your last object (i.e Jane Doe) is replacing the value value of first Object(i.e John Brown).
So now in Array both elements refers same memory reference that why you getting both same object(i.e Jon Doe). If you changes implementation to struct, you getting answer as per you are implementing, Because struct are Value Type. So it refers only value of object.
To be more specify About class and struct Please read this link
Just replace 'class' with 'struct' as class are reference type and struct are value type.
struct myRecord {
var firstName: String?
var lastName: String?
}
var myRecords = [myRecord]()
var tempRecord = myRecord()
tempRecord.firstName = "John"
tempRecord.lastName = "Brown"
myRecords.append(tempRecord)
tempRecord.firstName = "Jane"
tempRecord.lastName = "Doe"
myRecords.append(tempRecord)
for x in 0..<myRecords.count {
print(x, "=", myRecords[x].firstName!, myRecords[x].lastName!) }
When you re-assigned the value of tempRecord.firstName and tempRecord.lastName, it overwrote the value at index 0 of the myRecords array to equal the new values you set.
Index 0 and Index 1 of the myRecords array both point to the same tempRecord class instance in memory which holds the value
{
firstName: Jane,
lastName: Doe
}
In order to add multiple instances of the myRecord class, you could create a separate instance called tempRecords1 and append the values to the myRecords array like so:
...
var tempRecord = myRecord()
var tempRecord1 = myRecord()
...
tempRecord1.firstName = "Jane"
tempRecord1.lastName = "Doe"
myRecords.append(tempRecord1)
just put after
tempRecord.firstName = "John"
tempRecord.lastName = "Brown"
myRecords.append(tempRecord)
tempRecord = myRecords ()
then add jane doe.
you can use Struct instead of Class, depends on what you need.
I have two arrays of dictionaries:
let arrayA = [["name1": "email1"], ["name2": "email2"]]
let arrayB = [["name1": "email1"], ["name3": "email3"]]
I want to compare them and get another two arrays: arrayC should have the elements in arrayA but not in arrayB, and arrayD should have the elements in arrayB but not in arrayA:
let arrayC = [["name2": "email2"]]
let arrayD = [["name3": "email3"]]
How can I do this taking into the consideration large arrays?
Here you go
let arrayA = [["name1": "email1"], ["name2": "email2"]]
let arrayB = [["name1": "email1"], ["name3": "email3"]]
let arrayC = arrayA.filter{
let dict = $0
return !arrayB.contains{ dict == $0 }
}
let arrayD = arrayB.filter{
let dict = $0
return !arrayA.contains{ dict == $0 }
}
I know this answer may be complicating things and that you can use filter but...have you considered using Sets instead of Arrays?
Sets can give you operations for finding elements in setA but not in setB or elements in setA and setB out of the box.
There are a few caveats about sets though. As it says in The Swift Programming Guide
A set stores distinct values of the same type in a collection with no defined ordering. You can use a set instead of an array when the order of items is not important, or when you need to ensure that an item only appears once.
notice from the above:
Distinct: Meaning no duplicates
No definded ordering: Means that you cannot expect your sets to be in order
Also, notice this (also from The Swift Programming Guide):
A type must be hashable in order to be stored in a set—that is, the type must provide a way to compute a hash value for itself.
If you can live with that...then sets are a fine solution I think.
Here is an example...I created a simple Email struct and made that implement Hashable:
struct Email {
let name: String
let email: String
}
extension Email: Hashable {
var hashValue: Int {
return "\(name)\(email)".hashValue
}
static func ==(lhs: Email, rhs: Email) -> Bool {
return lhs.name == rhs.name && lhs.email == rhs.email
}
}
And that can then be used like so:
let arrayA = [Email(name: "name1", email: "email1"), Email(name: "name2", email: "email2")]
let arrayB = [Email(name: "name1", email: "email1"), Email(name: "name3", email: "email3")]
let setA = Set(arrayA)
let setB = Set(arrayB)
let inBothAAndB = setA.intersection(setB) //gives me an Email with "name1", "email1"
let inAButNotB = setA.subtracting(setB) //gives me an Email with "name2", "email2"
let inBButNotA = setB.subtracting(setA) //gives me an Email with "name3", "email3"
So...I don't know if that confuses things for you or makes things harder or maybe impossible (if you're data can contain more than one element with the same name and email for instance) but...I just thought you should consider sets :)
Hope that helps you.
is it possible to have a dictionary, that contains multiple values for one key?
For example I have multiple IDs (101,102,103,104...) and all of those IDs have some values (colour: green, number: 4, city: New York). I am new to programming and not sure how should I store it.
I was thinking about custom class:
class myClass: NSObject {
var ID: Int
var colour: String
var number: Int
var city: String
init(ID: Int, colour: String, number: Int, city: String) {
self.ID = ID
self.colour = colour
self.number = number
self.city = city
}
}
And the create some variable var myData = myClass() and just everything there, but then how could I access lets say ID 102 and modify its colour?
So my question how to store data provided in my example with an option to be able select specific ID and modify values belonging to that ID.
A dictionary must contain exactly one value for each key. However, that value could be an array, or a dictionary, or an object etc. etc. so that is no practical restriction.
Since instance of classes are stored as references, the dictionary values could be references to class instances. So you can extract the reference to an instance from the dictionary, and then modify the instance. Be aware that anyone holding a reference to the same instance will see the same changes.
Assuming you have two instances of your class
let item101 = MyClass(ID: 101, colour: "red", number: 4, city: "NewYork")
let item102 = MyClass(ID: 102, colour: "green", number: 7, city: "Chicago")
You can store them in a dictionary using the ID as key
let dictionary = [101: item101, 102: item102]
and retrieve a value by ID with
if let id101 = dictionary[101] {
// use id101
} else {
print("ID 101 not found")
}
or you can use an array
let array = [item101, item102]
and get an item by ID with the filter function
let filtered = array.filter{ $0.ID == 102 }
if !filtered.isEmpty {
let id102 = filtered[0]
} else {
print("ID 102 not found")
}
Declare you id with Array and foreach in that ID
var ID: [Int]
I have an array of PFObjects and I've created a new array: restaurantNames to store all their names. Now I'm trying to print the names on UIPageView, but I get the error:
'Int' is not convertible to 'Range<Int>'
Code:
private func getItemController(itemIndex: Int) -> PageItemController? {
let restaurantNames = finalRestaurantArray.map { $0.objectForKey("Name") }
if itemIndex < finalRestaurantArray.count {
let pageItemController = self.storyboard!.instantiateViewControllerWithIdentifier("ItemController") as PageItemController
pageItemController.itemIndex = itemIndex
pageItemController.restaurantName = restaurantNames[itemIndex]
//pageItemController.imageName = finalRestaurantArray[itemIndex]
return pageItemController
}
return nil
}
The actual PFObject array looks like this (restaurantNames contains the array of just names):
[<Restaurant: 0x7feb9252cfc0, objectId: LA74J92QDA, localId: (null)> {
Name = "Restaurant 1";
City = "New York";
Closed = 1;
Country = "United States";
FoodType = Japanese;
}, <Restaurant: 0x7feb926afa00, objectId: 0aKFrpKN46, localId: (null)> {
Name = "Restaurant 2";
City = "San Francisco";
Closed = 1;
Country = "United States";
FoodType = Italian;
}]
Pastebin: http://pastebin.com/U63TFMRV
This line is confusing to the compiler:
let restaurantNames = finalRestaurantArray.map { $0.objectForKey("Name") }
This creates an [AnyObject?] which is a notoriously difficult for the compiler to deal with, and the errors you get are often confusing (because of various promotions and overloads).
Step 1 is that you should avoid AnyObject whenever possible. So finalRestaurantArray should be an array of the actual objects rather than [AnyObject], or even dictionaries. Then your map would return a [String] like I believe you want it to.
You can hack this into place like this:
// Avoid this
let restaurantNames = finalRestaurantArray.map { $0.objectForKey("Name") as String }
And if anything goes wrong, it'll crash. Don't do that. Get your data out of AnyObject as fast as you can (and get it out of Dictionary as fast as you can, too), and turn it into real model objects that can guarantee they'll return a value.