iosswift5swift-optionals

Extracting a String from a [String: Any?] by key


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


Solution

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