I am still getting familiar with Swift, and I am having troubles with adding objects to an array at this moment. Also the array shouldn't have duplicates.
What I have so far -
A function that is called when user does a button click on a prototype cell. I am trying to achieve -
- Select button (and indicate with a checkmark that he selected/deselected the item)
- For each selected item, I have two values - bool status
isActiveand the selected item'ssubscriptionID - When user selects the item, I need to add this selection as an object and further append this to an array.
- For that, I have
subscriptionUpdateData: NSDictionaryand my new empty arraysubscriptionsArray: [NSDictionary] = []
Full Function
func subscriptionCell(cell: SubscriptionCell, didToggleSubscription subscription: Subscriptions) {
var subscriptionsArray: [NSDictionary] = []
var subscriptionUpdateData: NSDictionary = ["subscriptionID": 0, "isActive": false]
if let matchingSubscription = subscriptionInformation?.filter({ $0.subscriptionID == subscription.subscriptionID }).first {
matchingSubscription.isActive = !(matchingSubscription.isActive!)
let subscriptionStatus = matchingSubscription.isActive
let subscriptionStatusForId = matchingSubscription.subscriptionID
subscriptionUpdateData = ["subscriptionID": subscriptionStatusForId!, "isActive": subscriptionStatus!]
tableView.reloadData()
}
subscriptionsArray.append(subscriptionUpdateData)
print("\(subscriptionsArray)")
}
What is going on with above - I am able to select an item, form it as a dictionary, and add it to my array. :-) But whenever I select a different item in my list of items, it replaces the existing element in the array with the newly selected item. :-(
I am looking for something like below (without duplicates) which is an input to a REST endpoint -
[{ "subscriptionID" : 1234,
"isActive" : true
},
{
"subscriptionID" : 5678,
"isActive" : false
},
{
"subscriptionID" : 3489,
"isActive" : true
}]
Can someone look into where I am missing something? Or whether there is a better way I can do this?
var subscriptionsArray: [NSDictionary] = []outside ofsubscriptionCellmethod may be at instance levelNSDictionary.isActiveproperty to your data source model. An extra array is pretty cumbersome. And to get more familiar with Swift get rid ofNSDictionaryand use native SwiftDictionaryor – still better – a custom class or struct.