Check if key exists in dictionary of type [Type:Type?] - swift

How can I check if a key exists in a dictionary? My dictionary is of type [Type:Type?].
I can't simply check dictionary[key] == nil, as that could result from the value being nil.
Any ideas?

Actually your test dictionary[key] == nil can be used to check
if a key exists in a dictionary. It will not yield true if the value
is set to nil:
let dict : [String : Int?] = ["a" : 1, "b" : nil]
dict["a"] == nil // false, dict["a"] is .some(.some(1))
dict["b"] == nil // false !!, dict["b"] is .some(.none)
dict["c"] == nil // true, dict["c"] is .none
To distinguish between "key is not present in dict" and "value for key is nil" you
can do a nested optional assignment:
if let val = dict["key"] {
if let x = val {
print(x)
} else {
print("value is nil")
}
} else {
print("key is not present in dict")
}

I believe the Dictionary type's indexForKey(key: Key) is what you're looking for. It returns the index for a given key, but more importantly for your proposes, it returns nil if it can't find the specified key in the dictionary.
if dictionary.indexForKey("someKey") != nil {
// the key exists in the dictionary
}
Swift 3 syntax....
if dictionary.index(forKey: "someKey") == nil {
print("the key 'someKey' is NOT in the dictionary")
}

You can always do:
let arrayOfKeys = dictionary.allKeys
if arrayOfKeys.containsObject(yourKey) {
}
else {
}
However I really dislike the idea of creating an NSDictionary which can contain optionals.

Try this:
let value = dict[key] != nil
Hope it work for you. Thanks

As suggested here and above, the best solution is to use Dictionary.index(forKey:) which returns Dictionary<Key, Value>.Index?. Regardless of whether your value is an optional type, this returns an optional index, which if nil, definitively tells you whether the key exists in the dictionary or not. This is much more efficient than using Dictionary.contains(where:) which is documented to have "complexity O(n), where n is the length of the sequence."
So, a much better way to write .containsKey() would be:
extension Dictionary {
func contains(key: Key) -> Bool {
self.index(forKey: key) != nil
}
}
I've been advised that dict.keys.contains() is actually O(1), so feel free to use it if you prefer.

I handled it this way in Swift 4:
extension Dictionary {
func contains(key: Key) -> Bool {
let value = self.contains { (k,_) -> Bool in key == k }
return value
}
}
This uses Dictionary.contains(where: (key: Hashable, value: Value) throws -> Bool). By encapsulating it as an extension I have a good shot at updating the implementation to something better without modifying my code. I'm avoiding creating data, which index(forKey:Key) does. I'm hoping it's more efficient than accessing keys since that must create the whole array before searching it.

Related

Do i have to state a "return nil" statement when my return value in a function is an optional?

So for example i have the following code:
var meals: [String: Meal] = ["Breakfast": Meal(food: ["Bagel", "Orange Juice", "Egg Whites"], calories: 530)]
func logging (mealTime: String) -> Meal? {
if let a = meals[mealTime] {
return a
} else {
return nil
}
}
Do i need to state a "return nil" if my return value is already an optional? Because the solution to this exercise was just this:
func logging(mealTime: String) -> Meal? {
return meals[mealTime]
}
And if I do not have to add the return nil, why is that?
Thanks in advance!
Just to clarify:
Parameter:
mealTime: String
This string could be a key in your dictionary.
Function (how it works): this function wants to check if this key exists and if it is so, it returns the value (that is a Meal object).
What did you do?
if let a = meals[mealTime] {
return a
} else {
return nil
}
You are checking (if let) if there is a value with that string key and you are assigning that value to your constant (a). Eventually you return that value. If no value has that key in your array then you return nil.
What is the right answer about?
Because this function returns an Optional Meal, you can skip checking if it exists, that's why the right answer is just:
func logging(mealTime: String) -> Meal? {
return meals[mealTime]
}
This function returns nil if there is not value with that key and returns the value if it has that key.

Check if dictionary contains value in Swift

Just simple task. I've got a dictionary var types = [Int : String]() which inits like an empty and after some user actions it fills with data. According to emptiness or some specific data in this dictionary I enable/disable a button in UI.
Check for emptiness is easy, but how to check if dictionary contains certain value?
Compiler suggested me a placeholder with predicate:
types.contains(predicate: ((Int, String)) throws -> Bool>)
Since you only want to check for existance of a given value, you can apply the contains method for the values properties of your dictionary (given native Swift dictionary), e.g.
var types: [Int : String] = [1: "foo", 2: "bar"]
print(types.values.contains("foo")) // true
As mentioned in #njuri: answer, making use of the values property of the dictionary can seemingly yield an overhead (I have not verified this myself) w.r.t. just checking the contains predicate directly against the value entry in the key-value tuple of each Dictionary element. Since Swift is fast, this shouldn't be an issue, however, unless you're working with a huge dictionary. Anyway, if you'd like to avoid using the values property, you could have a look at the alternatives given in the forementioned answer, or, use another alternative (Dictionary extension) as follows:
extension Dictionary where Value: Equatable {
func containsValue(value : Value) -> Bool {
return self.contains { $0.1 == value }
}
}
types.containsValue("foo") // true
types.containsValue("baz") // false
I wrote a function which is using contains method on dictionary.
Your specific case:
let dic : [Int : String] = [1 : "a", 2 : "b"]
func dictionary(dict : [Int : String], containsValue value : String)->Bool{
let contains = dict.contains { (_,v) -> Bool in
return v == value
}
return contains
}
let c = dictionary(dic, containsValue: "c") // false
let a = dictionary(dic, containsValue: "a") // true
Generic:
extension Dictionary{
func containsValue<T : Equatable>(value : T)->Bool{
let contains = self.contains { (k, v) -> Bool in
if let v = v as? T where v == value{
return true
}
return false
}
return contains
}
}
I've tested this function against dictionary.values.contains() and it is roughly two times faster.
If you want to check if already contains a value this would be the way:
if !yourDictionary.values.contains("Zero") {
yourDictionary[newItemKey] = newItemValue; //addNewItem
}
else {
print("this value already exists");
}
And this one if you want to check if the key exists:
You get the item to add to your dictionary.
Check if the item's key already exists
If it doesn't, append the item or enable the button.
//1
let newItemKey = 0
let newItemValue = "Zero"
//2
let keyExists = yourDictionary[newItemKey] != nil
//3
if !keyExists {
yourDictionary[newItemKey] = newItemValue; //addNewItem
}
else {
print("This key already exists");
}
The dictionary getter returns an optional value.
let dictionary = ["ben": "says hi"]
let containsAlpha = dictionary["alpha"] != nil
let containsBen = dictionary["ben"] != nil

Swift Dictionary default value

A pattern I've gotten used to with Python's defaultdicts is a dictionary that returns a default value if the value for a given key has not been explicitly set. Trying to do this in Swift is a little verbose.
var dict = Dictionary<String, Array<Int>>()
let key = "foo"
var value: Array<Int>! = dict[key]
if value == nil {
value = Array<Int>()
dict[key] = value
}
I realize I can make a class that does this, but then the actual Dictionary has to be accessed through a property to use any of the other normal Dictionary methods
class DefaultDictionary<A: Hashable, B> {
let defaultFunc: () -> B
var dict = Dictionary<A, B>()
init(defaultFunc: () -> B) {
self.defaultFunc = defaultFunc
}
subscript(key: A) -> B {
get {
var value: B! = dict[key]
if value == nil {
value = defaultFunc()
dict[key] = value
}
return value
}
set {
dict[key] = newValue
}
}
}
Is there a better pattern for this?
This changed in Swift 4, and there's now a way to read a key's value or provide a default value if the key isn't present. For example:
let person = ["name": "Taylor", "city": "Nashville"]
let name = person["name", default: "Anonymous"]
This is particularly useful when modifying dictionary values, because you can write code like this:
var favoriteTVShows = ["Red Dwarf", "Blackadder", "Fawlty Towers", "Red Dwarf"]
var favoriteCounts = [String: Int]()
for show in favoriteTVShows {
favoriteCounts[show, default: 0] += 1
}
I covered this change and others in my article What's new in Swift 4.
Using Swift 2 you can achieve something similar to python's version with an extension of Dictionary:
// Values which can provide a default instance
protocol Initializable {
init()
}
extension Dictionary where Value: Initializable {
// using key as external name to make it unambiguous from the standard subscript
subscript(key key: Key) -> Value {
mutating get { return self[key, or: Value()] }
set { self[key] = newValue }
}
}
// this can also be used in Swift 1.x
extension Dictionary {
subscript(key: Key, or def: Value) -> Value {
mutating get {
return self[key] ?? {
// assign default value if self[key] is nil
self[key] = def
return def
}()
}
set { self[key] = newValue }
}
}
The closure after the ?? is used for classes since they don't propagate their value mutation (only "pointer mutation"; reference types).
The dictionaries have to be mutable (var) in order to use those subscripts:
// Make Int Initializable. Int() == 0
extension Int: Initializable {}
var dict = [Int: Int]()
dict[1, or: 0]++
dict[key: 2]++
// if Value is not Initializable
var dict = [Int: Double]()
dict[1, or: 0.0]
Unless I'm misunderstanding defaultdict in Python, I don't see how nil coalescing wouldn't work for you. Let's say you had a dictionary of type [Int:Int], and you wanted it to return 0 by default. With nil coalescing it looks like this:
let dict = [1:10, 2:8, 3:64]
let valueForKey = dict[4] ?? 0
You mentioned in a comment that that wouldn't work because it wouldn't update the dictionary. I don't understand the problem, though: why would you need to update the dictionary if you knew that every instance of nil would be replaced by your default? Maybe I'm missing something here but it seems like defaults and nil coalescing are (in practice) the same.
You can change the syntax a little, if it makes things more clear:
extension Dictionary {
subscript(key: Key, or r: Value) -> Value {
get { return self[key] ?? r }
set { self[key] = newValue }
}
}
In this case, the example above could be written like this:
let dict = [1:10, 2:8, 3:64]
let valueForKey = dict[4, or: 0]
In this case, mutating methods can work on the keys, like this:
var dict = [2: 8, 3: 64, 1: 10]
dict[2, or: 0]++
dict // [2: 9, 3: 64, 1: 10]
dict[4, or: 0]++
dict // [2: 9, 3: 64, 1: 10, 4: 1]
This extension is similar to the default subscript in Swift 4, with the difference that it will actually store the default value in the dictionary.
(It's also similar to QByte's answer, with the difference that it uses an autoclosure to prevent accessing the default when not needed).
extension Dictionary {
subscript(key: Key, setDefault defaultValue: #autoclosure () -> Value) -> Value {
mutating get {
return self[key] ?? {
let value = defaultValue()
self[key] = value
return value
}()
}
}
}
Note that no setter is defined for the subscript as the standard default subscript already fulfills this purpose.
Example:
var items = [String: ComplexItem]()
let item1 = items["milk", setDefault: ComplexItem()]
let item2 = items["milk", setDefault: ComplexItem()]
Here the ComplexItem is only created once because the dictionary retained it after the first access.

How to test the Optionality of a String?

I have two different scenarios where I need to test the "optionality" of an optional type. I have not been able to figure how to explicitly test if the variable is a .None or a .Some other than with an unwieldy switch statement. How can I test for Someness with an if statement?
Scenario 1
I am writing an address formatter and my inputs are a number of String? types. In this example a simple test for (str != nil) will work. However, since my other need is when dealing with a 'double optional' and a nil test can't distinguish between .Some(.None) and .None a solution to this problem will solve that problem too.
Here's a version that works using a switch
let address1:String? = "123 Main St"
let address2:String? = nil
let apt:String? = "101"
let components = [address1, address2, apt].filter( { (c) -> Bool in
switch c {
case .Some: return true
case .None: return false
}
}).map { return $0! } //Had to map because casting directly to [String] crashes
print(", ".join(components)) //"123 Main St, 101"
What's I'd like to see is something like with an if:
let nice = ["123 Main St", nil, "303"].filter { (c) -> Bool in
return (c == .Some)
}
print(", ".join(nice))
Scenario 2
This is where a nil test won't work. If something is a String?? it can be any of .None, .Some(.None), or .Some(.Some(String)). In my case, the variable is carrying the recordID from an api call which might either be missing entirely (.None), a value (.Some(.Some("ABDEFG")), or explicitly NULL (.Some(.None)).
let teamNoneNone: String?? = .None
let teamSomeNone: String?? = .Some(.None)
let teamSomeSome: String?? = "My favorite local sportsball team"
if teamNoneNone == nil {
print("teamNoneNone is nil but is it .None? We don't know!") //prints
} else {
print("teamNoneNone is not nil")
}
if teamSomeNone == nil {
print("teamSomeNone is nil")
} else {
print("teamSomeNone is not nil but is it .Some(.None)? We don't know!") //prints
}
if teamSomeSome == nil {
print("teamSomeSome is nil but is it .None? We don't know!")
} else {
print("teamSomeSome is not nil but is it .Some(.None) or .Some(.Some())? We don't know!") //prints
}
Via another SO post I found a workaround like this, but it's not very clear what's happening to a casual reader:
if let team: String? = teamSomeNone {
print("teamSomeNone is Some(.None)") //prints
} else {
print("teamSomeNone is .Some(.Some())")
}
if let tests if a value is .None, and if it isn’t, it unwraps it and binds it to a local variable within an if statement.
Using switch with .Some and .None is really a secondary way of handling optionals, if if let doesn’t cut it. But it almost always does, especially now you can do multiple if lets in a single statement, following the latest release of Swift 1.2 to production.
Wanting to filter out the nils in a collection is a common-enough task that Haskell has a standard function for it, called catMaybe. Here’s a version, which I’ll call catSome, that would do the trick in Swift:
func catSome<T>(source: [T?]) -> [T] {
var result: [T] = []
// iterate over the values
for maybe in source {
// if this value isn’t nil, unwrap it
if let value = maybe {
// and append it to the array
result.append(value)
}
}
return result
}
let someStrings: [String?] = ["123 Main St", nil, "101"]
catSome(someStrings) // returns ["123 Main St", "101"]
Doubly-wrapped optionals are a bit of a pain, so the best solution is to avoid them in the first place – often, via use of optional chaining or flatMap.
But if you do find yourself with some, and all you care about is the inner value, you can unwrap them using a double if let:
// later parts of the let can rely on the earlier
if let outer = teamSomeSome, teamName = outer {
println("Fully unwrapped team is \(teamName)")
}
If you want to explicitly know if a double-optional has an inner nil inside an outer value, but isn’t nil itself, you can use if let with a where clause:
if let teamSomeMaybe = teamSomeNone where teamSomeMaybe == nil {
// this will be executed only if it was .Some(.None)
println("SomeNone")
}
The where clause is an extra conditional that can be applied to the unwrapped value.

Determining if Swift dictionary contains key and obtaining any of its values

I am currently using the following (clumsy) pieces of code for determining if a (non-empty) Swift dictionary contains a given key and for obtaining one (any) value from the same dictionary.
How can one put this more elegantly in Swift?
// excerpt from method that determines if dict contains key
if let _ = dict[key] {
return true
}
else {
return false
}
// excerpt from method that obtains first value from dict
for (_, value) in dict {
return value
}
You don't need any special code to do this, because it is what a dictionary already does. When you fetch dict[key] you know whether the dictionary contains the key, because the Optional that you get back is not nil (and it contains the value).
So, if you just want to answer the question whether the dictionary contains the key, ask:
let keyExists = dict[key] != nil
If you want the value and you know the dictionary contains the key, say:
let val = dict[key]!
But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let:
if let val = dict[key] {
// now val is not nil and the Optional has been unwrapped, so use it
}
Why not simply check for dict.keys.contains(key)?
Checking for dict[key] != nil will not work in cases where the value is nil.
As with a dictionary [String: String?] for example.
The accepted answer let keyExists = dict[key] != nil will not work if the Dictionary contains the key but has a value of nil.
If you want to be sure the Dictionary does not contain the key at all use this (tested in Swift 4).
if dict.keys.contains(key) {
// contains key
} else {
// does not contain key
}
Looks like you got what you need from #matt, but if you want a quick way to get a value for a key, or just the first value if that key doesn’t exist:
extension Dictionary {
func keyedOrFirstValue(key: Key) -> Value? {
// if key not found, replace the nil with
// the first element of the values collection
return self[key] ?? first(self.values)
// note, this is still an optional (because the
// dictionary could be empty)
}
}
let d = ["one":"red", "two":"blue"]
d.keyedOrFirstValue("one") // {Some "red"}
d.keyedOrFirstValue("two") // {Some "blue"}
d.keyedOrFirstValue("three") // {Some "red”}
Note, no guarantees what you'll actually get as the first value, it just happens in this case to return “red”.
My solution for a cache implementation that stores optional NSAttributedString:
public static var attributedMessageTextCache = [String: NSAttributedString?]()
if attributedMessageTextCache.index(forKey: "key") != nil
{
if let attributedMessageText = TextChatCache.attributedMessageTextCache["key"]
{
return attributedMessageText
}
return nil
}
TextChatCache.attributedMessageTextCache["key"] = .some(.none)
return nil
If you want to return the value of the key you can use this extension
extension Dictionary {
func containsKey(_ key: Key) -> Value? {
if let index = index(forKey: key){
return self.values[index]
}
return nil
}
}
if dictionayTemp["quantity"] != nil
{
//write your code
}
If you are dealing with dictionary that may contain nil value for a key then you can check existence of key by:
dictionay.index(forKey: item.key) != nil
For getting first value in dictionary:
dictionay.first?.value // optional since dictionary might be empty