gpt4 book ai didi

swift - 如何将其中包含 nil 的 Any 值转换为 Any?

转载 作者:搜寻专家 更新时间:2023-11-01 05:52:47 24 4
gpt4 key购买 nike

我正在使用反射来尝试检查结构是否具有 nil 值。

struct MyStruct {
let myString: String?
}

let properties = Mirror(reflecting: MyStruct(myString: nil)).children.filter { $0.label != nil }

for property in properties {
if property.value == nil { // value has type "Any" will always fail.
print("property \(property.label!) is nil")
}
}

如何将 Any 类型转换为 Any?

最佳答案

简单地检查 nil包裹在 Any 中的属性值中的内容,您可以,与其他答案中描述的方法相反,实际上围绕类型转换/绑定(bind)/检查到具体的非 Any 进行工作。通过直接对 Optional<Any>.none 应用模式匹配来键入或 Optional<Any>.some(...) .

示例设置(不同的成员类型:我们不想仅仅为了检查 nil 内容而注释所有这些不同的类型)

struct MyStruct {
let myString: String?
let myInt: Int?
let myDouble: Double?
// ...
init(_ myString: String?, _ myInt: Int?, _ myDouble: Double?) {
self.myString = myString
self.myInt = myInt
self.myDouble = myDouble
}
}

简单日志记录:提取 nil 的属性名称有值(value)的属性

模式匹配Optional<Any>.none , 如果您只想在 nil 上登录信息有值(value)的实体:

for case (let label as String, Optional<Any>.none) in 
Mirror(reflecting: MyStruct("foo", nil, 4.2)).children {
print("property \(label) is nil")
}
/* property myInt is nil */

稍微更详细的日志记录:for nil以及非 nil有值(value)的属性

模式匹配Optional<Any>.some(...) , 如果您想要更详细的日志记录(下面的绑定(bind) x 值对应于您保证的非 nil Any 实例)

for property in Mirror(reflecting: MyStruct("foo", nil, 4.2)).children {
if let label = property.label {
if case Optional<Any>.some(let x) = property.value {
print("property \(label) is not nil (value: \(x))")
}
else {
print("property \(label) is nil")
}
}
}
/* property myString is not nil (value: foo)
property myInt is nil
property myDouble is not nil (value: 4.2) */

或者,后者使用 switch案例改为:

for property in Mirror(reflecting: MyStruct("foo", nil, 4.2)).children {
switch(property) {
case (let label as String, Optional<Any>.some(let x)):
print("property \(label) is not nil (value: \(x))")
case (let label as String, _): print("property \(label) is nil")
default: ()
}
}
/* property myString is not nil (value: foo)
property myInt is nil
property myDouble is not nil (value: 4.2) */

关于swift - 如何将其中包含 nil 的 Any 值转换为 Any?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40923597/

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