How to append elements into a dictionary in Swift?
You're using NSDictionary
. Unless you explicitly need it to be that type for some reason, I recommend using a Swift dictionary.
You can pass a Swift dictionary to any function expecting NSDictionary
without any extra work, because Dictionary<>
and NSDictionary
seamlessly bridge to each other. The advantage of the native Swift way is that the dictionary uses generic types, so if you define it with Int
as the key and String
as the value, you cannot mistakenly use keys and values of different types. (The compiler checks the types on your behalf.)
Based on what I see in your code, your dictionary uses Int
as the key and String
as the value. To create an instance and add an item at a later time you can use this code:
var dict = [1: "abc", 2: "cde"] // dict is of type Dictionary<Int, String>
dict[3] = "efg"
If you later need to assign it to a variable of NSDictionary
type, just do an explicit cast:
let nsDict = dict as! NSDictionary
And, as mentioned earlier, if you want to pass it to a function expecting NSDictionary
, pass it as-is without any cast or conversion.
How to append elements into dictionary at specific index swift
You can't do this with Dictionary
as it has no sorting criteria , only you can add element for a key , this way can be in Array
only
How do you add a Dictionary of items into another Dictionary
You can define +=
operator for Dictionary
, e.g.,
func += <K, V> (left: inout [K:V], right: [K:V]) {
for (k, v) in right {
left[k] = v
}
}
how to append new element to key value pair in swift
The issue there is that KeyValuePairs
unlike a regular dictionary, doesn't conform to Hashable
. You cannot assign through subscript. You may have duplicated key/value pairs. It conforms to RandomAccessCollection
so through subscript you can only get but not set a value.
keyValuePair = [element.tabName: issueFieldArray]
works because KeyValuePairs
conform to ExpressibleByDictionaryLiteral
but you can NOT append a new key value pair because it doesn't conform to RangeReplaceableCollection
. In other words you need to add all key value pairs when initialising your collection.
How do I add values in dictionary?
Just take an array of dictionary
var arrOfDict = [[String :AnyObject]]()
var dictToSaveNotest = [String :AnyObject]()
@IBAction func addItem(_ sender: Any)
{
dictToSaveNotest .updateValue(textField.text! as AnyObject, forKey: "title")
dictToSaveNotest .updateValue(NotesField.text! as AnyObject, forKey: "notesField")
arrOfDict.append(dictToSaveNotest)
}
And just populate it in the tableView Data source method By just make two outlet in the tableViewCell Class titleLable and notesLabel
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! yourTableViewCell
cell.titleLabel.text = arrayOfDict[indexPath.row]["title"] as! String!
cell.notesLabel.text = arrayOfDict[indexPath.row]["notesField"] as! String!
return cell
}
Note : I have not tested it on the code , but hope it will work definitely.
All the best .
Appending dictionary values to array in Swift
You should only sort the keys and then use that array to select from the dictionary and append your sortedValues
array. I made the sortedKeys
into a local variable
func sortItems() {
let sortedKeys = self.dictionary.keys.sorted(by: >)
for key in sortedKeys {
if let obj = dictionary[key] {
self.sortedValues.append(obj)
}
}
}
I don't know if this will make a difference in regard to the crash but another way is to let the function return an array
func sortItems() -> [Object] {
let sortedKeys = self.dictionary.keys.sorted(by: >)
var result: [Object]()
for key in sortedKeys {
if let obj = dictionary[key] {
result.append(obj)
}
}
return result
}
and then call it
self.sortedValues = sortItems()
How to add another dictionary entry to an existing dictionary to form a new dictionary (i.e. not append)
There is a built-in merging(_:uniquingKeysWith:)
function on Dictionary
that does exactly what you need.
let dictionary = [1:1]
let otherDictionary = [1:2, 2:3]
// This will take the values from `otherDictionary` if the same key exists in both
// You can use `$0` if you want to take the value from `dictionary` instead
let mergedDict = dictionary.merging(otherDictionary, uniquingKeysWith: { $1 })
If you want, you can easily define a +
operator for Dictionary
that uses the above function.
extension Dictionary {
static func + (lhs: Self, rhs: Self) -> Self {
lhs.merging(rhs, uniquingKeysWith: { $1 })
}
}
let addedDict = dictionary + otherDictionary
Append to array in [String: Any] dictionary structure
The type of data[Items]
isn't Array
but actually Array<[String: Any]>
.
You could probably squeeze this into fewer steps, but I prefer the clarity of multiple steps:
var data: [String: Any] = [
"key1": "example value 1",
"key2": "example value 2",
"items": []
]
for index in 1...3 {
let item: [String: Any] = [
"key": "new value"
]
// get existing items, or create new array if doesn't exist
var existingItems = data["items"] as? [[String: Any]] ?? [[String: Any]]()
// append the item
existingItems.append(item)
// replace back into `data`
data["items"] = existingItems
}
Related Topics
Extend Array Types Using Where Clause in Swift
Unwrapping Multiple Optionals in If Statement
Swiftui Iterating Through Dictionary With Foreach
Xcode Swift Am/Pm Time to 24 Hour Format
When Should I Access Properties With Self in Swift
What Is the Meaning of the '#' Mark in Swift Language
Check If 'Any' Value Is Object
Swift Closure Async Order of Execution
Why My Return Is Nil But If I Press the Url in Chrome/Safari, I Can Get Data
Instance Member Cannot Be Used on Type of Custom Class
How to Get Current Language Code With Swift
How to Get the Name of Enumeration Value in Swift
What's the Simplest Way to Convert from a Single Character String to an Ascii Value in Swift
How to Convert Double to Int in Swift
Difference Between a Weak Reference and an Unowned Reference