gpt4 book ai didi

swift - 如何检查属性是否已使用 Swift 反射设置?

转载 作者:可可西里 更新时间:2023-11-01 00:11:15 25 4
gpt4 key购买 nike

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

下面是一次尝试,但我无法弄清楚如何从 Any 对象中确定一个 nil 值[编辑:(child 变量的类型为 任何)]。它不编译。

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 总是失败。我试图在下面的 Playground 上进行说明。

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 反射(reflect)Any 值的技术来修改原始函数。它使用初始镜像循环遍历属性,然后使用 displayStyle 单独反射(reflect)每个属性以确定属性是否可选。

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 - 如何检查属性是否已使用 Swift 反射设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34601802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com