How to Retrieve a Value from Dictionary in Swift 3

How to retrieve a value from dictionary in Swift 3

Since your JSON is

"inovoID" : { "name" : "Tatiana", "points" : 6 }
  • playa.key is "inovoID"
  • playa.value is { "name" : "Tatiana", "points" : 6 }

The key is String and cannot be subscripted. That's what the error says.

You need to subscribe the value and safely cast the type to help the compiler.

if let person = playa.value as? [String:Any] {
print(person["name"] as! String)
}

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)")
}

How to access a dictionary value with Swift 3?

Try this:-

    func setAnnotations(){

//get data
FIRDatabase.database().reference().child("Stores").observe(.value, with: { (snapshot) in

self.mapView.removeAnnotations(self.annArray)

for item in snapshot.children{

if let itemDict = (item as! FIRDataSnapshot).value as? [String:AnyObject]{

annotation.subtitle = itemDict["Category"] as! String
annotation.title = itemDict["Name"] as! String
annotation.annImg = itemDict["Logo"] as! String
if let locationDict = itemDict["Location"] as? [String:AnyObject]{

let getLatitude = locationDict["latitude"] as! Double
let getLongitude = locationDict["longitude"] as! Double

annotation.coordinate = CLLocationCoordinate2D(latitude: getLatitude, longitude: getLongitude)
self.annArray.append(annotation)

self.mapView.addAnnotation(annotation)
}
}
}
})

}

Swift 3 - Get value from array of dictionaries

Is this what you are trying to do?

var fromLocations = [["marco" : "polo1"],["marco" : "polo2"],["marco" : "polo3"]]
let marco = fromLocations[0]["marco"]
print("marco = \(marco)")

This prints "polo1". Basically you are accessing the first item of the array which is a dictionary. You then access that dictionary the way you would normally access a dictionary.

So a break down would be:

let fromLocations = [["marco" : "polo"],["marco" : "polo"],["marco" : "polo"]]
let theDictionary = fromLocations[0]
let value = theDictionary["marco"]

To just get the values as an array with using the key (which is strange), turn the values into an array.

var fromLocations = [["marco" : "polo1"],["marco" : "polo2"],["marco" : "polo3"]]
let marco = Array(fromLocations[0].values)[0]
print("marco = \(marco)")

This will print "polo1"

Grab the value from a DictionaryString, Any in Swift 3

Try this combination of string interpolation, optional chaining, conditional casting and the nil coalescing operator ??:

let dest = "\(dico?["adresse"] as? String ?? "") \(dico?["cp"] as? String ?? "") \(dico?["ville"] as? String ?? "")"

If the value for key "cp" is really an Int, then do this:

let dest = "\(dico?["adresse"] as? String ?? "") \(dico?["cp"] as? Int ?? 0) \(dico?["ville"] as? String ?? "")"

Swift dictionary get key for value

Swift 3: a more performant approach for the special case of bijective dictionaries

If the reverse dictionary lookup use case covers a bijective dictionary with a one to one relationship between keys and values, an alternative approach to the collection-exhaustive filter operation would be using a quicker short-circuiting approach to find some key, if it exists.

extension Dictionary where Value: Equatable {
func someKey(forValue val: Value) -> Key? {
return first(where: { $1 == val })?.key
}
}

Example usage:

let dict: [Int: String] = [1: "one", 2: "two", 4: "four"]

if let key = dict.someKey(forValue: "two") {
print(key)
} // 2

Retrieve first dictionary value swift

This should do the trick:

It's a good initiative when learning programming to use manual for loop instead of magical methods like map(), etc, in an algorithmic way. They do loop, but they are implicit.

Here, I used the sorted() (because else it can be a little long).

I also used first(where:), it finds the first non-empty value. It also can be replaced with a while loop, but I didn't know if you wanted a for loop to.

var dict = [1: ["Value-1-1", "", ""],
2: ["", "Value-2-2", "Value-2-3"],
3: ["Value-3-1", "Value-3-2", ""],
4: ["Value-4-1", "", "Value-4-3"],
5: ["", "", "Value-5-3"]]
var finalArray = [String]()
let keys = Array(dict.keys).sorted(by: { return $0<$1 }) // because keys aren't sorted
for aKey in keys {
if let anArrayValue = dict[aKey], let firstNonEmptyValue = anArrayValue.first(where: { !$0.isEmpty }) {
finalArray.append(firstNonEmptyValue)
}
}
print("finalArray: \(finalArray)")

See @Martin R answer for the version with "higher level" methods, but more complicated to understand for debutants (chaining, closures, etc.). It does the same, just more compact, less explicit.

How to extract a subset of a swift 3 Dictionary

Your assumption is correct, there is a more concise/swift-ish way to accomplish what you need.

For example you can do it via reduce, a functional programming concept available in Swift:

let subDict = originalDict.reduce([String: CustomObject]()) {
guard mySet.contains($1.key) else { return $0 }
var d = $0
d[$1.key] = $1.value
return d
}

Or, in two steps, first filtering the valid elements, and then constructing back the dictionary with the filtered elements:

let filteredDict = originalDict.filter { mySet.contains($0.key) }
.reduce([CustomObject]()){ var d = $0; d[$1.key]=$1.value; return d }

forEach can also be used to construct the filtered dictionary:

var filteredDict = [CustomObject]()
mySet.forEach { filteredDict[$0] = originalDict[$0] }

, however the result would be good it it would be immutable:

let filteredDict: [String:CustomObject] = { 
var result = [String:CustomObject]()
mySet.forEach { filteredDict2[$0] = originalDict[$0] }
return result
}()

Dictionary contains a certain value swift 3

contains(where:) checks if any element of the collection satisfies
the given predicate, so in your case it would be

let b = countDic.contains { (key, value) -> Bool in
value as? String == givenString
}

or, directly applied to the values view of the dictionary:

let b = countDic.values.contains { (value) -> Bool in
value as? String == givenString
}

In both cases it is necessary to (optionally) cast the AnyObject
to a String in order to compare it with the given string.

It would be slightly easier with a dictionary of type
Dictionary<String, String> because strings are Equatable,
and the contains(element:) method can be used:

let b = countDic.values.contains(givenString)


Related Topics



Leave a reply



Submit