如何将Any中的Any值转换为Any?

tun*_*ten 1 reflection swift

我使用反射来尝试检查结构是否具有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")
    }
}
Run Code Online (Sandbox Code Playgroud)

如何将Any类型转换为Any?

dfr*_*fri 7

要简单地检查nil包含在a中的属性值中的内容Any,您可以与其他答案中描述的方法相反,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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

模式匹配Optional<Any>.none,如果您只想记录nil有价值实体的信息:

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 */
Run Code Online (Sandbox Code Playgroud)

稍微更详细的日志记录:nil以及非nil值属性

模式匹配Optional<Any>.some(...),以防您需要更详细的日志记录(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) */
Run Code Online (Sandbox Code Playgroud)

或者,后者使用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) */
Run Code Online (Sandbox Code Playgroud)