0

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.

4
  • You just need to change your array type to let arr: [Any?] = [1, nilString]. You have declared your array type as optional instead of declaring its elements. Commented Feb 15, 2020 at 20:30
  • Can you share why you think you need to use an array of Any? This seems like a code smell and there is possibly a much better way to deal with the problem than using an array of Any? Commented Feb 15, 2020 at 20:32
  • @LeoDabus moving the question mark in the brackets works for me. I've edited the question so your answer would fit. Write it and I will mark as correct, thank you Commented Feb 15, 2020 at 20:39
  • 1
    @Fogmeister bad code. It's literally that, at the moment during prototyping there are a lot of different types and nested types to take care of as the model isn't done yet Commented Feb 15, 2020 at 20:41

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.