Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if `Any(not Any?)` is nil or not in swift

Tags:

swift

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)
}
like image 235
JIE WANG Avatar asked May 09 '18 13:05

JIE WANG


People also ask

How do you check if an int variable is null or empty in Swift?

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 "" .

How do I check if a variable is empty in Swift?

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.

What is a nil value in Swift?

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.


1 Answers

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
like image 87
vacawama Avatar answered Nov 16 '22 01:11

vacawama