0
var annoying: [String: Any?]

To get the 'height' value, the best I could come up with is this,

let found: String = (annoying["height"] as? String? ?? "?") ?? "?"
  1. That seems very bad, is there a better way?

  2. Indeed, ideally I'd like

    let found: String? = :O

So it's nil if the key does not exist -or- the value is nil -or- the value is not a String - but, I literally, don't know how to do that and every attempt failed :/

(I just make do with the "?" marker in the first solution.)

1
  • Something like let found: String? = annoying["height", default: ""] as? String? Commented Jul 4, 2024 at 18:00

1 Answer 1

2
+250

You can simply do

let found = annoying["height"] as? String

Requirements

it's nil if the key does not exist

let annoying: [String: Any?] = [:]
let found = annoying["height"] as? String
// nil

-or- the value is nil

let annoying: [String: Any?] = ["height":nil]
let found = annoying["height"] as? String
// nil

-or- the value is not a String

let annoying: [String: Any?] = ["height":42]
let found = annoying["height"] as? String
// nil

And it works for string keys:

let annoying: [String: Any?] = ["height":"10m"]
let found = annoying["height"] as? String
// "10m"
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.