下面是一个尝试,但我无法弄清楚如何从Any对象确定一个nil值[编辑:(子变量的类型为Any)].它不编译.
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}
编辑:
我忘了澄清上面示例中的子值始终是Any类型. Any类型很难,因为它无法与nil进行比较,并且对AnyObject的强制转换总是失败.我试图在下面的 *** 场上说明它.
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//}过时:
您只需检查可选值是否为零:
func allPropertIEsHaveValues(obj: AnyObject) -> Bool { let mirror = Mirror(reflecting: obj) for child in mirror.children { //child.value being an optional if child.value == nil { return false } } return true}
编辑:
要检查Any对象是否是可选的并且是否包含使用反射的值:
let optionalString : String? = "optional string"let any : Any = optionalString//First you will need to create a mirror of the any objectlet mirror = Mirror(reflecting : any)//Then you can check the display style to see if it's an optionalif mirror.displayStyle == .Optional { //If it is,check the count of its children to see if there is a value or not if mirror.children.count == 0 { print("I don't have a value") } else { print("I have a value") }}
这是一个游乐场示例(基于您的):
var anyArray = [Any]()var optionalStringWithValue: String? = "foo"anyArray.append(optionalStringWithValue)var nilOptional: String?anyArray.append(nilOptional)let string = "string not optional"anyArray.append(string)print(anyArray[0]) // "Optional("foo")\n"print(anyArray[1]) // "nil\n"print(anyArray[2]) // "string not optional\n"let mirrorOptionalWithValue = Mirror(reflecting: anyArray[0])if mirrorOptionalWithValue.displayStyle == .Optional && mirrorOptionalWithValue.children.count == 1 { print("Is an optional and contains a value")}let mirrorOptionalWithoutValue = Mirror(reflecting: anyArray[1])if mirrorOptionalWithoutValue.displayStyle == .Optional && mirrorOptionalWithoutValue.children.count == 0 { print("Is an optional but is nil")}let mirrorNotAnoptional = Mirror(reflecting: anyArray[2])if mirrorNotAnoptional.displayStyle != .Optional { print("Is not an optional")}总结
以上是内存溢出为你收集整理的如何检查是否已使用Swift反射设置属性?全部内容,希望文章能够帮你解决如何检查是否已使用Swift反射设置属性?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)