如何检查是否使用 Swift 反射设置了属性? [英] How can I check if a property has been set using Swift reflection?

查看:46
本文介绍了如何检查是否使用 Swift 反射设置了属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一些模型具有可选属性.我正在尝试编写一种可以评估它们是否已设置的方法.

Some of my models have optional properties. I'm trying to write a method that can evaluate if they've been set.

下面是一个尝试,但我不知道如何从 Any 对象中确定一个 nil 值.它不编译.

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
}

<小时>

我忘了说明上面例子中的 child 值总是 Any 类型.Any 类型很困难,因为它无法与 nil 进行比较,并且转换为 AnyObject 总是失败.我已尝试在下面的操场上对其进行说明.

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

//}

推荐答案

我使用了@ebluehands 反映Any 值的技术来修改原始函数.它使用初始镜像循环遍历属性,然后使用 displayStyle 单独反射每个属性以确定属性是否可选.

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
}

这篇关于如何检查是否使用 Swift 反射设置了属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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