UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Dictionary - how can i acess this values ?

Forums > SwiftUI

@State var userSession : [String: Any]?

when i print userSession!["data"] i receive

Optional({
    "access_token" = "MTg3MGFkMzJkNzMzMTA0NGMzZGI2NjFkZWJlOGZmMDUxMzViMjkzNGEzY2M1MWU4MTYyNDg5NDgxNw==";
    "access_token_expires_in" = 1200;
    "refresh_token" = "NGQyYjFmY2VlZTg1YTNhYzM2ZmY5M2U4NjYzMWE5ZGNhY2RhYjA4MjgwZWVkYTJmMTYyNDg5NDgxNw==";
    "refresh_token_expires_in" = 1209600;
    "session_id" = 19;
})

how can i acess this values ?

3      

The problem is that since the values in userSession can be Any, Swift has no idea that the "data" key is a Dictionary. So it can't access the subscripts. So you somehow need to let Swift know that this is a Dictionary.

Either of these methods will work:

let sesh1 = userSession!["data"]! as! [String:Any]
print(sesh1["session_id"])

let sesh2 = (userSession! as NSDictionary).value(forKeyPath: "data.session_id")
print(sesh2)

But be sure to properly deal with all the Optionals in your actual code. All that force unwrapping hurts my soul.

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.