Reputation: 3218
I have an Optional array and need to check a member for nil. Unfortunately that doesn't work like I have expected it to do. It seems like I have to unwrap it however at runtime I don't know whether the value in question is a String, an Int, another array etc. so casting doesn't help (I think)
var nilString: String? = nil
let arr = [1, nilString] as [Any]?
print(nilString)
print(arr?[1])
if (arr?[1] == nil) {
print("is nil") // doesn't work
}
if case Optional<Any>.none = arr?[1] {
print("nil") //would expect this one
} else { //but
print("not nil") //<-- gets printed
}
Alternative ideas on the structure are also welcomed.
Upvotes: 0
Views: 346
Reputation: 236548
Your problem there is that you have declared your Array
type as optional instead of declaring its elements. You just need to change your array declaration to[Any?]
. Note that the use of Any
it is not useful in most situations. I've been coding in Swift for more than 5 years and I've never needed to declare an element type as Any
.
Upvotes: 1