Suppose I have String like :
var abc : NSString = "ABC"
and I want to check that it is nil or not and for that I try :
if abc == nil{
//TODO:
}
But this is not working and giving me an error. Error Says :
Can not invoke '=='with an argument list of type '(#|value NSString , NilLiteralConvertible)'
Any solution for this?
If abc is an optional, then the usual way to do this would be to attempt to unwrap it in an if statement:
if let variableName = abc { // If casting, use, eg, if let var = abc as? NSString
// variableName will be abc, unwrapped
} else {
// abc is nil
}
However, to answer your actual question, your problem is that you're typing the variable such that it can never be optional.
Remember that in Swift, nil is a value which can only apply to optionals.
Since you've declared your variable as:
var abc: NSString ...
it is not optional, and cannot be nil.
Try declaring it as:
var abc: NSString? ...
or alternatively letting the compiler infer the type.
The case of if abc == nil is used when you are declaring a var and want to force unwrap and then check for null. Here you know this can be nil and you can check if != nil use the NSString functions from foundation.
In case of String? you are not aware what is wrapped at runtime and hence you have to use if-let and perform the check.
You were doing following but without "!". Hope this clears it.
From apple docs look at this:
let assumedString: String! = "An implicitly unwrapped optional string."
You can still treat an implicitly unwrapped optional like a normal optional, to check if it contains a value:
if assumedString != nil {
println(assumedString)
}
// prints "An implicitly unwrapped optional string."
The null check is really done nice with guard keyword in swift. It improves the code readability and the scope of the variables are still available after the nil checks if you want to use them.
func setXYX -> Void{
guard a != nil else {
return;
}
guard b != nil else {
return;
}
print (" a and b is not null");
}
I ended up writing utility function for nil check
func isObjectNotNil(object:AnyObject!) -> Bool
{
if let _:AnyObject = object
{
return true
}
return false
}
Does the same job & code looks clean!
Usage
var someVar:NSNumber?
if isObjectNotNil(someVar)
{
print("Object is NOT nil")
}
else
{
print("Object is nil")
}
func isObjectValid(someObject: Any?) -> Any? {
if someObject is String {
if let someObject = someObject as? String {
return someObject
}else {
return ""
}
}else if someObject is Array<Any> {
if let someObject = someObject as? Array<Any> {
return someObject
}else {
return []
}
}else if someObject is Dictionary<AnyHashable, Any> {
if let someObject = someObject as? Dictionary<String, Any> {
return someObject
}else {
return [:]
}
}else if someObject is Data {
if let someObject = someObject as? Data {
return someObject
}else {
return Data()
}
}else if someObject is NSNumber {
if let someObject = someObject as? NSNumber{
return someObject
}else {
return NSNumber.init(booleanLiteral: false)
}
}else if someObject is UIImage {
if let someObject = someObject as? UIImage {
return someObject
}else {
return UIImage()
}
}
else {
return "InValid Object"
}
}
This function checks any kind of object and return's default value of the kind of object, if object is invalid.
if (MyUnknownClassOrType is nil) {
println("No class or object to see here")
}
Apple also recommends that you use this to check for depreciated and removed classes from previous frameworks.
Here's an exact quote from a developer at Apple:
Yes. If the currently running OS doesn’t implement the class then the class method will return nil.
Hope this helps :)
Normally, I just want to know if the object is nil or not.
So i use this function that just returns true when the object entered is valid and false when its not.
func isNotNil(someObject: Any?) -> Bool {
if someObject is String {
if (someObject as? String) != nil {
return true
}else {
return false
}
}else if someObject is Array<Any> {
if (someObject as? Array<Any>) != nil {
return true
}else {
return false
}
}else if someObject is Dictionary<AnyHashable, Any> {
if (someObject as? Dictionary<String, Any>) != nil {
return true
}else {
return false
}
}else if someObject is Data {
if (someObject as? Data) != nil {
return true
}else {
return false
}
}else if someObject is NSNumber {
if (someObject as? NSNumber) != nil{
return true
}else {
return false
}
}else if someObject is UIImage {
if (someObject as? UIImage) != nil {
return true
}else {
return false
}
}
return false
}
Swift 4.2
func isValid(_ object:AnyObject!) -> Bool
{
if let _:AnyObject = object
{
return true
}
return false
}
Usage
if isValid(selectedPost)
{
savePost()
}
Swift short expression:
var abc = "string"
abc != nil ? doWork(abc) : ()
or:
abc == nil ? () : abc = "string"
or both:
abc != nil ? doWork(abc) : abc = "string"
Swift-5 Very Simple Way
//MARK:- In my case i have an array so i am checking the object in this
for object in yourArray {
if object is NSNull {
print("Hey, it's null!")
}else if object is String {
print("Hey, it's String!")
}else if object is Int {
print("Hey, it's Int!")
}else if object is yourChoice {
print("Hey, it's yourChoice!")
}
else {
print("It's not null, not String, not yourChoice it's \(object)")
}
}
Swift 4
You cannot compare Any to nil.Because an optional can be nil and hence it always succeeds to true.
The only way is to cast it to your desired object and compare it to nil.
if (someone as? String) != nil
{
//your code`enter code here`
}
Swift 5
Crash
Your app crash because parameters receive null, and broke in NSException.
if let parameters = parameters {
httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
}
Solution
if let parameters = parameters, JSONSerialization.isValidJSONObject(parameters) {
httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
}
Related
I want to check my dictionary to containing nil or empty value (nil and ""), add show it on the UI
my dictionary contains string and int values
let params = [
"token":APItoken.getToken(),
"gender":gender_id,
"car_number":number_car,
"car_model":car_model,
"year_of_birth":1998,
"car_year":create_year,
"seats_number":sits,
"facilities":fac,
"type":typeID
] as [String : Any]
I try to use this code, but it doesn't work
if params.values.filter({ $0 == nil }).isEmpty
{
print("full")
}
else
{
print("empty")
}
Change the type of Dictionary from [String:Any] to [String:Any?] to compare values to nil
let someDict = ["first":"name","second":1,"third":1.2,"someNilValue":nil] as [String:Any?]
func checkEmptyDict(_ dict:[String:Any?]) -> Bool {
for (_,value) in dict {
if value == nil || value as? String == "" { return true }
}
return false
}
checkEmptyDict(someDict) //returns true
you should change params type [String : Any] to [String : Any?]
your Code for check nil is correct just need to add empty string condition
like :
if params.values.filter({
if let x = $0 {
if let str = x as? String , str.isEmpty {
return true
} else {
return false
}
} else {
return true
}
}).isEmpty
{
print("not contain nil value ")
}
else
{
print("contain nil value ")
}
I have a static function that extends NSManagedObject to get an object like so...
NSManagedObject.get(type: MYUser.self, with: ("id", "SomeUserId"), in: context)
extension NSManagedObject {
static func get<M: NSManagedObject>(type: M.Type, with kvp: (String, CVarArg), in context: NSManagedObjectContext) -> M? {
guard let name = entity().name else { return nil }
guard M.entity().propertiesByName[kvp.0] != nil else { Assert("\(name) does not have \(kvp.0)"); return nil }
let fetchRequest = NSFetchRequest<M>(entityName: name)
fetchRequest.predicate = NSPredicate(format: "\(kvp.0) == %#", kvp.1)
do {
let object = try context.fetch(fetchRequest)
if let foundObject = object.first { return foundObject }
return nil
} catch {
return nil
}
}
}
The syntax I would like is
MYUser.get(with: ("id", "SomeUserId"), in: context)
and to infer the Type from the class that made the call... but I'm unsure what to put in place of the generic here
NSFetchRequest<M>(entityName: name)
NSFetchRequest<???>(entityName: name)
Thanks in advance
If you don't mind writing MYUser twice, you can remove the type parameter and specify the type so that Swift can infer M:
extension NSManagedObject {
static func get<M: NSManagedObject>(with kvp: (String, CVarArg), in context: NSManagedObjectContext) -> M? {
guard let name = entity().name else { return nil }
guard M.entity().propertiesByName[kvp.0] != nil else {
print("\(name) does not have \(kvp.0)")
return nil
}
let fetchRequest = NSFetchRequest<M>(entityName: name)
fetchRequest.predicate = NSPredicate(format: "\(kvp.0) == %#", kvp.1)
do {
let object = try context.fetch(fetchRequest)
if let foundObject = object.first { return foundObject }
return nil
} catch {
return nil
}
}
}
// usage:
let user: MYUser? = MYUser.get(with: ("id", "SomeUserId"), in: context)
If you don't want to write MYUser twice, then I can't think of any solutions. If NSManagedObject were a protocol, you could have used Self in there.
Based on the link Passing generic Class as argument to function in swift suggested by Martin R
protocol Managed where Self: NSManagedObject { }
extension Managed where Self: NSManagedObject {
static func get(with kvp: (String, CVarArg), in context: NSManagedObjectContext) -> Self? {
guard let name = entity().name else { return nil }
guard entity().propertiesByName[kvp.0] != nil else { Assert("\(name) does not have \(kvp.0)"); return nil }
let fetchRequest = NSFetchRequest<Self>(entityName: name)
fetchRequest.predicate = NSPredicate(format: "\(kvp.0) == %#", kvp.1)
do {
let object = try context.fetch(fetchRequest)
if let foundObject = object.first { return foundObject }
return nil
} catch {
return nil
}
}
I am new to Swift. I tried with this Swift link Detect a Null value in NSDictionaryNSDictionary, but I failed to do so.
Data:
"end_time" = "<null>"
Here is my code:
if endTime["end_time"] is NSNull {
print("your session still available ")
}
else{
print("your session end \(endTime["end_time"])")
}
Every time it is going to else statement. May be I need to convert string to null or alternative solution. Could you help me please?
Thank you.
Here's how you check null in swift:
let time = endTime["end_time"]
if time != "<null>" {
print("time is not <null>")
}
else
{
print("time is <null>")
}
You can create a NilCheck controller to check nil or null for various datatypes. For example i have created a function to remove null [if any] from the dictionary and store the array of dictionary in Userdefaults. Please be free to ask your queries :)
func removeNilAndSaveToLocalStore(array : [[String:Any]]) {
var arrayToSave = [[String:Any]]()
for place in array {
var dict = [String:Any]()
dict["AreaId"] = NilCheck.sharedInstance.checkIntForNil(nbr: place["AreaId"]! as? Int)
dict["AreaNameAr"] = NilCheck.sharedInstance.checkStringForNil(str: place["AreaNameAr"]! as? String)
dict["AreaName"] = NilCheck.sharedInstance.checkStringForNil(str: place["AreaName"]! as? String)
dict["GovernorateId"] = NilCheck.sharedInstance.checkIntForNil(nbr: place["GovernorateId"]! as? Int)
arrayToSave.append(dict)
}
LocalStore.setAreaList(token: arrayToSave)
}
class NilCheck {
static let sharedInstance : NilCheck = {
let instance = NilCheck()
return instance
}()
func checkStringForNil(str : String?) -> String {
guard let str = str else {
return String() // return default string
}
return str
}
func checkIntForNil(nbr : Int?) -> Int {
guard let num = nbr else {
return 0 // return default Int
}
return num
} }
Some of my models have optional properties. I'm trying to write a method that can evaluate if they've been set.
Below is an attempt, but I can't figure out how to determine a nil value from an Any object [edit: (the child variable is of type Any)]. It doesn't compile.
func allPropertiesHaveValues(obj: AnyObject) -> Bool {
let mirror = Mirror(reflecting: obj)
for child in mirror.children {
let value = child.value
if let optionalValue = value as? AnyObject? { //Does not compile
if optionalValue == nil {
return false
}
}
}
return true
}
Edit:
I forgot to clarify that the child value in the above example is always of type Any. The Any type is difficult in that it cannot be compared to nil and a cast to AnyObject always fails. I've tried to illustrate it in the playground below.
var anyArray = [Any]();
var optionalStringWithValue: String? = "foo";
anyArray.append(optionalStringWithValue);
var nilOptional: String?
anyArray.append(nilOptional)
print(anyArray[0]); // "Optional("foo")\n"
print(anyArray[1]); // "nil\n"
if let optionalString = anyArray[0] as? AnyObject {
//will always fail
print("success")
}
//if anyArray[1] == nil { // will not compile
//}
I used #ebluehands technique of reflecting the Any value to modify the original function. It cycles through the properties with an initial mirror, then reflects each one individually using displayStyle to determine if the property is optional.
func allPropertiesHaveValues(obj: AnyObject) -> Bool {
let mirror = Mirror(reflecting: obj)
for child in mirror.children {
let value: Any = child.value
let subMirror = Mirror(reflecting: value)
if subMirror.displayStyle == .Optional {
if subMirror.children.count == 0 {
return false
}
}
}
return true
}
Obsolete:
You can simply check if the optional value is nil or not :
func allPropertiesHaveValues(obj: AnyObject) -> Bool {
let mirror = Mirror(reflecting: obj)
for child in mirror.children {
//child.value being an optional
if child.value == nil {
return false
}
}
return true
}
Edit:
To check if an Any object is optional and contains a value or not using reflection :
let optionalString : String? = "optional string"
let any : Any = optionalString
//First you will need to create a mirror of the any object
let mirror = Mirror(reflecting : any)
//Then you can check the display style to see if it's an optional
if mirror.displayStyle == .Optional {
//If it is, check the count of its children to see if there is a value or not
if mirror.children.count == 0 {
print("I don't have a value")
}
else {
print("I have a value")
}
}
Here is a playground example (based on yours):
var anyArray = [Any]()
var optionalStringWithValue: String? = "foo"
anyArray.append(optionalStringWithValue)
var nilOptional: String?
anyArray.append(nilOptional)
let string = "string not optional"
anyArray.append(string)
print(anyArray[0]) // "Optional("foo")\n"
print(anyArray[1]) // "nil\n"
print(anyArray[2]) // "string not optional\n"
let mirrorOptionalWithValue = Mirror(reflecting: anyArray[0])
if mirrorOptionalWithValue.displayStyle == .Optional
&& mirrorOptionalWithValue.children.count == 1 {
print("Is an optional and contains a value")
}
let mirrorOptionalWithoutValue = Mirror(reflecting: anyArray[1])
if mirrorOptionalWithoutValue.displayStyle == .Optional &&
mirrorOptionalWithoutValue.children.count == 0 {
print("Is an optional but is nil")
}
let mirrorNotAnOptional = Mirror(reflecting: anyArray[2])
if mirrorNotAnOptional.displayStyle != .Optional {
print("Is not an optional")
}
Another option is create a extension.
extension NSManagedObject {
func checkIfAllRequiredMembersAreSet() -> Bool {
let attributes = self.entity.attributesByName
for (attribute, value) in attributes {
if value.attributeValueClassName != nil {
let v: AnyObject? = self.valueForKey(attribute)
if !value.optional && v != nil {
return false
}
}
}
return true
}
}
Based on this answer, I recommend using if case Optional<Any>.some(_).
I did something recently to make sure I have at least one optional set. Here's an example to make sure all are set. You can paste into playgrounds:
import Foundation
struct SomeError: Error {
let code: Int?
let message: String?
let errorDescription: String?
var allValuesSet: Bool {
for aChild in Mirror(reflecting: self).children {
if case Optional<Any>.some(_) = aChild.value {
continue
} else {
return false
}
}
return true
}
}
let errorTest = SomeError(code: nil, message: "failed", errorDescription: nil)
let errorTest2 = SomeError(code: -1, message: "failed", errorDescription: "missing information")
print("is valid: \(errorTest.allValuesSet)") //is valid: false
print("is valid: \(errorTest2.allValuesSet)") //is valid: true
How can I put a default value into my string if getting data from an empty key/value in a dictionary.
so [myObject setMyString:[dictionary valueForKey:#"myKey"]];
So then if I did NSString *newString = myObject.myString I would get an unrecognized selector error.
So again, I simply need a way to insert a default string if the key value is empty;
If dictionary is a NSDictionary you should probably use objectForKey as valueForKey is used for KVC. It works for NSDictionary but may bite you if the key collide with some NSDictionary KVC key, e.g. "#allKeys" or "#count".
I think the shortest is probably to do:
[dictionary objectForkey:#"myKey"] ?: #"defaultValue"
There is one terrible way of abusing the existing dictionary methods to produce a get by key or return a default value if you don't want to use a condition for some reason...
[[dictionary objectsForKeys:[NSArray arrayWithObject:#"myKey"]
notFoundMarker:#"defaultValue"]
objectAtIndex:0]
You did not hear it from me :)
What about this?
NSString *value = [dictionary valueForKey:#"myKey"];
if (!value) value = #"defaultValue";
[myObject setMyString:value];
Use [NSNull null] for the general case, and handle it when that is returned.
In your question, you wouldn't get "unrecognised selector"; newString would be set to nil (as opposed to [NSNull null], so I suspect you might have meant something else - perhaps how to set defaults values for NSUserDefaults?
I've done this with a simple NSDictionary extension.
NSDictionary+NSDictionaryExtensions.h
#import <Foundation/Foundation.h>
#interface NSDictionary (NSDictionaryExtensions)
- (id)objectForKey:(id)aKey defaultObject: (id) defObj;
#end
NSDictionary+NSDictionaryExtensions.m
#import "NSDictionary+NSDictionaryExtensions.h"
#implementation NSDictionary (NSDictionaryExtensions)
- (id)objectForKey:(id)aKey defaultObject: (id) defObj
{
id ret = [self objectForKey: aKey];
if ( ret == nil )
return defObj;
else
return ret;
}
#end
I can then access as follows:
NSString* str = [dict objectForKey: #"a_key" defaultObject: #"default"];
try
if ( myObject == nil ) {
[myObject setMyString:#""];
}
or
if ( [dictionary valueForKey:#"myKey"] == nil ) {
[dictionary setObject:#"" forKey:#"myKey"];
}
Whatever default value you assigned to your string it will not make myObject.myString return "unrecognized selector error" - usually the property myString either exists or it does not ('usually' as you can dig into the guts of the Objective-C runtime and play games, but this is rarely (if ever) what you want to do!)
What are you trying to do? If your aim is to throw an exception on myObject.myString not being set then you can do that in the property implementation.
For example, valueForKey; will return nil if there is no value set for a given key, so you can check for that in your property:
- (void) setMyString:(NSString *)value
{ myString = value;
}
- (NSString *) myString
{
if (myString == nil)
#throw [NSException exceptionWithName:#"UnrecognizedSelector" reason:#"No value set for myString" userInfo:nil];
return myString;
}
Notes:
code typed at terminal, may contain typos
code assumes garbage collection/ARC on, if not you need to add appropriate retain/copy/release
But do you really want to throw an exception? You would normally only do so if the string should be set and not being so is an exceptional condition - you don't throw for default values.
As per #Paul Lynch you must check for [NSNull null] apart from nil. It is also advisable to check for the data type you are looking for:
- (id) objectForKey: (id) key withDefault: (id) defaultValue
{
id value = self[key];
if (value == nil || [value isEqual: [NSNull null]] || ![defaultValue isKindOfClass: [value class]])
{
value = defaultValue;
}
return value;
}
You can manually check for nil values as below for different types:
extension NSDictionary {
func convertToString() -> String {
let jsonData = try! JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData!
if jsonData == nil{
return "{}"
}else {
return String(data: jsonData as! Data, encoding: String.Encoding.utf8)!
}
}
func object_forKeyWithValidationForClass_Int(aKey: String) -> Int {
// CHECK FOR EMPTY
if(self.allKeys.count == 0) {
return Int()
}
// CHECK IF KEY EXIST
if let val = self.object(forKey: aKey) {
if((val as AnyObject).isEqual(NSNull())) {
return Int()
}
} else {
// KEY NOT FOUND
return Int()
}
// CHECK FOR NIL VALUE
let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
if aValue.isEqual(NSNull()) {
return Int()
}
else if(aValue.isKind(of: NSString.self)){
return Int((aValue as! NSString).intValue)
}
else {
if aValue is Int {
return self.object(forKey: aKey) as! Int
}
else{
return Int()
}
}
}
func object_forKeyWithValidationForClass_CGFloat(aKey: String) -> CGFloat {
// CHECK FOR EMPTY
if(self.allKeys.count == 0) {
return CGFloat()
}
// CHECK IF KEY EXIST
if let val = self.object(forKey: aKey) {
if((val as AnyObject).isEqual(NSNull())) {
return CGFloat()
}
} else {
// KEY NOT FOUND
return CGFloat()
}
// CHECK FOR NIL VALUE
let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
if aValue.isEqual(NSNull()) {
return CGFloat()
}
else {
if aValue is CGFloat {
return self.object(forKey: aKey) as! CGFloat
}
else{
return CGFloat()
}
}
}
func object_forKeyWithValidationForClass_String(aKey: String) -> String {
// CHECK FOR EMPTY
if(self.allKeys.count == 0) {
return String()
}
// CHECK IF KEY EXIST
if let val = self.object(forKey: aKey) {
if((val as AnyObject).isEqual(NSNull())) {
return String()
}
} else {
// KEY NOT FOUND
return String()
}
// CHECK FOR NIL VALUE
let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
if aValue.isEqual(NSNull()) {
return String()
}
else if(aValue.isKind(of: NSNumber.self)){
return String(format:"%f", (aValue as! NSNumber).doubleValue)
}
else {
if aValue is String {
return self.object(forKey: aKey) as! String
}
else{
return String()
}
}
}
func object_forKeyWithValidationForClass_StringInt(aKey: String) -> String {
// CHECK FOR EMPTY
if(self.allKeys.count == 0) {
return String()
}
// CHECK IF KEY EXIST
if let val = self.object(forKey: aKey) {
if((val as AnyObject).isEqual(NSNull())) {
return String()
}
} else {
// KEY NOT FOUND
return String()
}
// CHECK FOR NIL VALUE
let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
if aValue.isEqual(NSNull()) {
return String()
}
else if(aValue.isKind(of: NSNumber.self)){
return String(format:"%d", (aValue as! NSNumber).int64Value)
}
else {
if aValue is String {
return self.object(forKey: aKey) as! String
}
else{
return String()
}
}
}
func object_forKeyWithValidationForClass_Bool(aKey: String) -> Bool {
// CHECK FOR EMPTY
if(self.allKeys.count == 0) {
return Bool()
}
// CHECK IF KEY EXIST
if let val = self.object(forKey: aKey) {
if((val as AnyObject).isEqual(NSNull())) {
return Bool()
}
} else {
// KEY NOT FOUND
return Bool()
}
// CHECK FOR NIL VALUE
let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
if aValue.isEqual(NSNull()) {
return Bool()
}
else {
if aValue is Bool {
return self.object(forKey: aKey) as! Bool
}
else{
return Bool()
}
}
}
func object_forKeyWithValidationForClass_NSArray(aKey: String) -> NSArray {
// CHECK FOR EMPTY
if(self.allKeys.count == 0) {
return NSArray()
}
// CHECK IF KEY EXIST
if let val = self.object(forKey: aKey) {
if((val as AnyObject).isEqual(NSNull())) {
return NSArray()
}
} else {
// KEY NOT FOUND
return NSArray()
}
// CHECK FOR NIL VALUE
let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
if aValue.isEqual(NSNull()) {
return NSArray()
}
else {
if aValue is NSArray {
return self.object(forKey: aKey) as! NSArray
}
else{
return NSArray()
}
}
}
func object_forKeyWithValidationForClass_NSMutableArray(aKey: String) -> NSMutableArray {
// CHECK FOR EMPTY
if(self.allKeys.count == 0) {
return NSMutableArray()
}
// CHECK IF KEY EXIST
if let val = self.object(forKey: aKey) {
if((val as AnyObject).isEqual(NSNull())) {
return NSMutableArray()
}
} else {
// KEY NOT FOUND
return NSMutableArray()
}
// CHECK FOR NIL VALUE
let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
if aValue.isEqual(NSNull()) {
return NSMutableArray()
}
else {
if aValue is NSMutableArray {
return self.object(forKey: aKey) as! NSMutableArray
}
else{
return NSMutableArray()
}
}
}
func object_forKeyWithValidationForClass_NSDictionary(aKey: String) -> NSDictionary {
// CHECK FOR EMPTY
if(self.allKeys.count == 0) {
return NSDictionary()
}
// CHECK IF KEY EXIST
if let val = self.object(forKey: aKey) {
if((val as AnyObject).isEqual(NSNull())) {
return NSDictionary()
}
} else {
// KEY NOT FOUND
return NSDictionary()
}
// CHECK FOR NIL VALUE
let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
if aValue.isEqual(NSNull()) {
return NSDictionary()
}
else {
if aValue is NSDictionary {
return self.object(forKey: aKey) as! NSDictionary
}
else{
return NSDictionary()
}
}
}
func object_forKeyWithValidationForClass_NSMutableDictionary(aKey: String) -> NSMutableDictionary {
// CHECK FOR EMPTY
if(self.allKeys.count == 0) {
return NSMutableDictionary()
}
// CHECK IF KEY EXIST
if let val = self.object(forKey: aKey) {
if((val as AnyObject).isEqual(NSNull())) {
return NSMutableDictionary()
}
} else {
// KEY NOT FOUND
return NSMutableDictionary()
}
// CHECK FOR NIL VALUE
let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
if aValue.isEqual(NSNull()) {
return NSMutableDictionary()
}
else {
if aValue is NSMutableDictionary {
return self.object(forKey: aKey) as! NSMutableDictionary
}
else{
return NSMutableDictionary()
}
}
}
}