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 ")
}
Related
I'm using an map function and must map an empty string to nil, otherwise the string. Problem is that the input is Any?
var arr : Any? = ["hallo", "", nil, "hihi"]
let res = arr.map{ (($0 ?? "") as! String).isEmpty ? nil : $0 }
print(res)
Do you know how to do this?
The map function is this here:
id <- (map["id"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } }))
https://github.com/Hearst-DD/ObjectMapper#custom-transforms
Do you mean like this:
var arr : Any? = ["hallo", "", nil, "hihi"]
if let array = arr as? [String?] {
let result = array.map { ($0?.isEmpty ?? true) ? nil : $0 }
print(result)
}
Storing an array is Any? is questionable, but if you must...
let arr: Any? = ["hallo", "", nil, "hihi"]
guard let casted = arr as? [String?] else {
// handle error
fatalError("arr is not a [String?]")
}
let result: [String?] = casted.map{
guard let s = $0 else { return nil }
return s.isEmpty ? nil : s
}
print(result as Any)
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
What I want
func safeGet<T>() -> T {
let value = magic()
if let typedValue = value as? T {
return typedValue
}
}
The reason this doesn't work is the fact that you can't do <NSNumber> as Int in swift
What do I put in the <what do I put here?> placeholder?
func safeGet<T>() -> T {
let value = magic()
if let typedValue = value as? NSNumber {
return <what do I put here?>
} else if let typedValue = value as? T {
return typedValue
}
}
In the end I did this to be able to get typed values from the dictionary in a way that throws errors. It's used like this
let name:String = dictionary.safeGet("name")
or
let name = dictionary.safeGet("name") as String`
The source code:
import Foundation
extension Dictionary {
func safeGet<T>(key:Key) throws -> T {
if let value = self[key] as? AnyObject {
if let typedValue = value as? T {
return typedValue
}
let typedValue: T? = parseNumber(value)
if typedValue != nil {
return typedValue!
}
let typeData = Mirror(reflecting: value)
throw generateNSError(
domain: "DictionaryError.WrongType",
message: "Could not convert `\(key)` to `\(T.self)`, it was `\(typeData.subjectType)` and had the value `\(value)`"
)
} else {
throw generateNSError(
domain: "DictionaryError.MissingValue",
message: "`\(key)` was not in dictionary. The dictionary was:\n\(self.description)"
)
}
}
private func parseNumber<T>(value: AnyObject) -> T? {
if Int8.self == T.self {
if let numericValue = value as? NSNumber {
return numericValue.charValue as? T
} else if let stringValue = value as? String {
return Int8(stringValue) as? T
}
} else if Int16.self == T.self {
if let numericValue = value as? NSNumber {
return numericValue.shortValue as? T
} else if let stringValue = value as? String {
return Int16(stringValue) as? T
}
} else if Int32.self == T.self {
if let numericValue = value as? NSNumber {
return numericValue.longValue as? T
} else if let stringValue = value as? String {
return Int32(stringValue) as? T
}
} else if Int64.self == T.self {
if let numericValue = value as? NSNumber {
return numericValue.longLongValue as? T
} else if let stringValue = value as? String {
return Int64(stringValue) as? T
}
} else if UInt8.self == T.self {
if let numericValue = value as? NSNumber {
return numericValue.unsignedCharValue as? T
} else if let stringValue = value as? String {
return UInt8(stringValue) as? T
}
} else if UInt16.self == T.self {
if let numericValue = value as? NSNumber {
return numericValue.unsignedShortValue as? T
} else if let stringValue = value as? String {
return UInt16(stringValue) as? T
}
} else if UInt32.self == T.self {
if let numericValue = value as? NSNumber {
return numericValue.unsignedIntValue as? T
} else if let stringValue = value as? String {
return UInt32(stringValue) as? T
}
} else if UInt64.self == T.self {
if let numericValue = value as? NSNumber {
return numericValue.unsignedLongLongValue as? T
} else if let stringValue = value as? String {
return UInt64(stringValue) as? T
}
} else if Double.self == T.self {
if let numericValue = value as? NSNumber {
return numericValue.doubleValue as? T
} else if let stringValue = value as? String {
return Double(stringValue) as? T
}
} else if Float.self == T.self {
if let numericValue = value as? NSNumber {
return numericValue.floatValue as? T
} else if let stringValue = value as? String {
return Float(stringValue) as? T
}
} else if String.self == T.self {
if let numericValue = value as? NSNumber {
return numericValue.stringValue as? T
} else if let stringValue = value as? String {
return stringValue as? T
}
}
return nil
}
private func generateNSError(domain domain: String, message: String) -> NSError {
return NSError(
domain: domain,
code: -1,
userInfo: [
NSLocalizedDescriptionKey: message
])
}
}
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)
}