Swift Guard Else Called on Dictionary Key with Null Value

Swift guard else called on dictionary key with NULL value

Your dictionary does contain ...

Optional({
age = "<null>";
names = (
David
);
})

... and ...

  • age = ... is String = String (value is single String),
  • names = ( ... ) is String = [String] (value is array of Strings).

You can't cast it to [String:[String]] because the first pair doesn't fit this type. This is the reason why your guard statement hits else.

Hard to answer your question. Dictionary contains names, you want categories, names key does contain David, which doesn't look like category, ... At least you know why guard hits else.

Dynamically remove null value from swift dictionary using function

Rather than using a global function (or a method), why not making it a method of Dictionary, using an extension?

extension Dictionary {
func nullKeyRemoval() -> Dictionary {
var dict = self

let keysToRemove = Array(dict.keys).filter { dict[$0] is NSNull }
for key in keysToRemove {
dict.removeValue(forKey: key)
}

return dict
}
}

It works with any generic types (so not limited to String, AnyObject), and you can invoke it directly from the dictionary itself:

var dic : [String: AnyObject] = ["FirstName": "Anvar", "LastName": "Azizov", "Website": NSNull(),"About": NSNull()]
let dicWithoutNulls = dic.nullKeyRemoval()

Swift: How to remove a null value from Dictionary?

You can create an array containing the keys whose corresponding values are nil:

let keysToRemove = dict.keys.array.filter { dict[$0]! == nil }

and next loop through all elements of that array and remove the keys from the dictionary:

for key in keysToRemove {
dict.removeValueForKey(key)
}

Update 2017.01.17

The force unwrapping operator is a bit ugly, although safe, as explained in the comments. There are probably several other ways to achieve the same result, a better-looking way of the same method is:

let keysToRemove = dict.keys.filter {
guard let value = dict[$0] else { return false }
return value == nil
}

Swift: Dictionary Key contain the value still it's error nil

It is because dictSearch expects Any as a variable but you’re passing String therefore, it crashes:

Maybe if all the variables are Strings, change it to:

var dictSearch = [String:String]()

If not, you’ll need to cast the date as any not string

This is not recommended, but try this:

guard let strDate = dict["fromdate"] as? String else { 
print("error")
return
}
yourlabel.text = strDate

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

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
}

How to check if NSDictionary is not nil in Swift 2

The error is due to assuming (force casting) a value that can sometimes be nil. Swift is awesome, because it allows conditional unwraps and conditional casts in very concise statements. I recommend the following (for Swift 1-3):

Use "if let" to conditionally check for "action" in the dictionary.

Use as? to conditionally cast the value to a String

if let actionString = val["action"] as? String {
// action is not nil, is a String type, and is now stored in actionString
} else {
// action was either nil, or not a String type
}

Detect a Null value in NSDictionary

You can use the as? operator, which returns an optional value (nil if the downcast fails)

if let latestValue = sensor["latestValue"] as? String {
cell.detailTextLabel.text = latestValue
}

I tested this example in a swift application

let x: AnyObject = NSNull()
if let y = x as? String {
println("I should never be printed: \(y)")
} else {
println("Yay")
}

and it correctly prints "Yay", whereas

let x: AnyObject = "hello!"
if let y = x as? String {
println(y)
} else {
println("I should never be printed")
}

prints "hello!" as expected.



Related Topics



Leave a reply



Submit