what the difference of keys and values in dictionary of swift
a) "I need to use optional values to keys and then unwrap it, however the values don't to be done so.But why?"
This is not true. You can initialize thekind
string variable with an empty string the same way you did with your integer type max
setting its initial value to zero.
b) "Don't know why to use "kinds" rather than kind in the closure, but the one before that used number rather than numbers ,and how can I use numbers to get same result?"
You are unnecessarily iterating each character of your dictionary keys. Thats why you are assigning kinds
String
instead of kind
Character
.
let interestingnumbers = [
"prime": [2,3,5,7,9,11,21],
"fibonacci": [1,23,5,32,4,123,11],
"dadgadfgh":[1,2,4,5,43,6,576,12],
"square": [1243325,123,455,1111],
]
var thekind: String = ""
var max = 0
for (key, numbers) in interestingnumbers {
for number in numbers {
if number > max {
max = number
thekind = key
}
}
}
print(max, thekind) // "1243325 square\n"
Just for fun the functional approach:
// result is a tuple (kind and max)
// reduce iterates every key value pair
// $0 is the accumulated which in this case it is used to hold the max value and the corresponding key
// $1 is the current key,value pair (kind, numbers)
let (kind, max) = interestingnumbers.reduce(into: ("",0)) {
// here we check if the current value has a maximum value and if it is greater than $0.1 (the resulting tuple maxValue)
if let maxValue = $1.value.max(), maxValue > $0.1 {
// if true assign a new tuple to the result with the new key and the new maximum value
$0 = ($1.key, maxValue)
}
}
print(kind, max) // "square 1243325\n"
How can I get key's value from dictionary in Swift?
Use subscripting to access the value for a dictionary key. This will return an Optional:
let apple: String? = companies["AAPL"]
or
if let apple = companies["AAPL"] {
// ...
}
You can also enumerate over all of the keys and values:
var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]
for (key, value) in companies {
print("\(key) -> \(value)")
}
Or enumerate over all of the values:
for value in Array(companies.values) {
print("\(value)")
}
Swift:Comparing Dictionary Keys
var dataSet = [DefaultNameModel]()
for i in self.selectedDictKeys
{
let dataRow = DefaultNameModel()
dataRow.key = i
if dataRow.key == "Result"
{
dataRow.value == "Success"
dataSet.append(dataRow)
print("The data Row is " + dataRow.Key + " " + dataRow.value)
}
if dataRow.key == "Date Added"
{
dataRow.value == "2016-12-12"
dataSet.append(dataRow)
print("The data Row is " + dataRow.Key + " " + dataRow.value)
}
if dataRow.key == "Entered By"
{
dataRow.value == "Me"
dataSet.append(dataRow)
print("The data Row is " + dataRow.Key + " " + dataRow.value)
}
}
How can I compare dictionary keys and array?
You don't even need to compare the key, You can get the values like:
for key in orderItemName {
//You can access the value from dictionary using -> arrays[key]
}
parse dictionary with different keys and values
As pointed by Eric, you should read the documentation first. To get key - value of a dictionary, you need to do this:
for (key, value) in mapNames {
print(key)
print(mapNames[key])
}
How to extract differences between dictionaries?
We can define an operator to check whether 2 dictionaries contains the same keys and for each key the same value.
Value must be Equatable
First of all we need to use generics to require that the Value
of the dictionaries conforms to Equatable
otherwise we won't be able to compare the values.
The code
Here's the code
func ==<Value:Equatable>(left: [String: Value], right: [String: Value]) -> Bool {
guard left.keys.count == right.keys.count else { return false }
let differenceFound = zip(left.keys.sort(), right.keys.sort()).contains { elm -> Bool in
let leftKey = elm.0
let rightKey = elm.1
return leftKey != rightKey || left[leftKey] != right[rightKey]
}
return !differenceFound
}
The first line verify that the dictionaries have the same number of entries, otherwise false
is returned.
The next block of code sort the keys of both dictionaries and compare each pair looking for a pair where the keys or the values are different.
If such difference is not found then the dictionaries have the same keys and values, so they are equals.
Examples
["a":1, "b": 2] == ["a":1, "b": 2] // true
Of course since values inside a dictionaries don't have an order the following is still true
["a":1, "b": 2] == ["b":2, "a": 1] // true
In the next example we compare 2 dictionaries with a different number of values
["a":1, "b": 2] == ["a":1, "b": 2, "c": 3] // false
The != operator
Since we defined the ==
operator, Swift gifts us the !=
operator (which simply returns the opposite of ==
), so we can also write
["a":1, "b": 2] != ["d":4] // true
Shorter version
The same operator can also be written in this shorter way
func ==<Value:Equatable>(left: [String: Value], right: [String: Value]) -> Bool {
return
left.keys.count == right.keys.count &&
!zip(left.keys.sort(), right.keys.sort()).contains { $0 != $1 || left[$0] != right[$1] }
}
Update
Now given 2 dictionaries a
and b
, you want to perform a.minus(b)
and get as result a new dictionaries containing all the (key, value)
pairs available in a
and not available in b
.
Here's the code
extension Dictionary where Key: Comparable, Value: Equatable {
func minus(dict: [Key:Value]) -> [Key:Value] {
let entriesInSelfAndNotInDict = filter { dict[$0.0] != self[$0.0] }
return entriesInSelfAndNotInDict.reduce([Key:Value]()) { (res, entry) -> [Key:Value] in
var res = res
res[entry.0] = entry.1
return res
}
}
}
Examples
["a":1].minus(["a":2]) // ["a": 1]
["a":1].minus(["a":1]) // [:]
["a":1].minus(["a":1, "b":2]) // [:]
["a":1, "b": 2].minus(["a":1]) // ["b": 2]
Related Topics
Why Does Function Has Multiple Return Types in Swift
Let User Save PDF Outside App in iOS Swift
How to Unpack Multiple Levels of Nested JSON in Firebase Database
App Window on Top of All Windows Including Others App Windows
With Data (Not Nsdata), in Fact How Actually Do You Make a Utf8 Version of a Jpeg
Need Clarification for Swift Type Properties
Fetch an Email Body in Mailcore2 Osx with Swift
Xcode 8.0 Cbcentralmanager Issue
Can't Change Uiimageview Image in Function (Swift)
Swiftui: Stop an Animation That Repeats Forever
"Unexpectedly Found Nil While Unwrapping an Optional Value" When Retriveing Pffile from Parse.Com
Swift 3:Delegate Within Tapgesturerecognizer in Generics Doesn't Get Called
Swift: Nil Error When Using Self.Moc.Save() to Save in Core Data
Label Showing Top of Screen Instead of Being on the Inputaccessoryview
Getting Wrong Date from Dateformat
Implementing a 'Report' Feature for Inappropriate Content Swift Firebase