检查字典中是否为零 [英] Check for nil in dictionary

查看:434
本文介绍了检查字典中是否为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个类,用户在其中输入值,然后将它们设置为该类的实例,然后将这些数据上传到数据库,但是我必须将该类转换为数据库可以接受的值,并且m使用镜面反射转换为字典.我的课程中的某些属性可以为nil,因为根据设计,并非所有属性都是必需的.但是我无法将nil值传递给数据库.

I have a class in my app, where the user inputs values and i set them to an instance of the class, then i upload this data to Database, but i have to convert the class to something the database accepts and i'm converting to dictionary using Mirror Reflection. Some properties in my class can be nil, because by design not all properties are required. But i can't pass nil values to the database.

我重新创建了一个非常简化的游乐场示例.我没有为该类的name属性设置值

I have recreated my example is very simplified playground. i didn't set a value for the name property of the class

我尝试在将键,值对添加到字典之前检查nil 以下是我的代码

I tried to check for nil before adding the key, value pair to the dictionary Below is my code

import UIKit

class Color: NSObject {
    var name: String?
    var code: Int?
    var shade: String?
}

let cl = Color()

cl.code = 3456
cl.shade = "DARK"

var colorDict = [String: Any]()

for x in Mirror(reflecting: cl).children.makeIterator() {
    if let val = x.value as Any? {
        print(type(of: val))
        colorDict[x.label!] = val
    }
}

print (colorDict)

控制台中的输出如下

Optional<String>
Optional<Int>
Optional<String>
["name": nil, "code": Optional(3456), "shade": Optional("DARK")]

我如何检查nil值并跳过将该属性添加到字典中

how can i check for nil values and skip adding that property to the Dictionary

在我添加了包括nils在内的所有值并尝试检查值之后,我尝试遍历字典,但是我得到以下警告

i have tried to loop through the dictionary after i add all values including nils and check for values too but i get the below warning

将类型为"Any"的非可选值与nil进行比较,总是返回false

声明字典如下

var colorDict = [String: Any?]()
for x in colorDict {
    if x.value == nil {
        colorDict.removeValue(forKey: x.key)
    }
}

删除警告,但不删除任何内容.

removes the warning but it doesn't remove anything.

非常感谢您的帮助.

推荐答案

解开包含可选对象的类型为Any的对象的方式很奇怪,但是您可以像这样检查镜像中的值是否为nil :

The way of unwrapping objects of type Any that contain optionals is kind of weird but you can check that the values aren't nil in your mirror like this:

for x in Mirror(reflecting: cl).children {    
    if case Optional<Any>.some(let val) = x.value {
        print(type(of: val))
        colorDict[x.label!] = val
    }
}

这篇关于检查字典中是否为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆