我的一些模型具有可选属性.我正在尝试编写一种可以评估它们是否已设置的方法.
下面是一个尝试,但我无法弄清楚如何从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 object let mirror = Mirror(reflecting : any) //Then you can check the display style to see if it's an optional if 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") }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。