I'm working with the Mirror
in swift, I found Mirror.Child
is very strange, the label is nullable, but the value seems not nullable.
public typealias Child = (label: String?, value: Any)
I don't know how to check if the value is nil or not.
let b: Bool? = true
let a: Any = b
print(a == nil) // false
I have one solution:
print(String(describing: a) == "nil") // true
but it is obviously not a good solution.
what is the best way to check if a
is nil or not ?
Let me put more detail,
let mirror = Mirror(reflecting: object) // object can be any object.
for child in mirror.children {
guard let label = child.label else {
continue
}
// how to check if the value is nil or not here ?
setValue(child.value, forKey: label)
}
You can use if let. if let is a special structure in Swift that allows you to check if an Optional holds a value, and in case it does – do something with the unwrapped value. But for Strings you can also use . isEmpty() If you have initialized it to "" .
Swift – Check if String is Empty To check if string is empty in Swift, use the String property String. isEmpty . isEmpty property is a boolean value that is True if there are no any character in the String, or False if there is at least one character in the String.
In Swift, nil means the absence of a value. Sending a message to nil results in a fatal error. An optional encapsulates this concept. An optional either has a value or it doesn't. Optionals add safety to the language.
Using if case
:
You can use if case Optional<Any>.none = a
to test if a
is nil
:
var b: Bool?
var a = b as Any
if case Optional<Any>.none = a {
print("nil")
} else {
print("not nil")
}
nil
b = true
a = b as Any
if case Optional<Any>.none = a {
print("nil")
} else {
print("not nil")
}
not nil
Using switch
:
You can use the pattern test with switch
as well:
var b: Bool?
var a = b as Any
switch a {
case Optional<Any>.none:
print("nil")
default:
print("not nil")
}
nil
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With