How to get a property of a tuple with a string?

I’m starting in Swift, I come from JavaScript, and some things are a bit confusing for me, is there something similar to this in Swift?:

JS:

var user = {name: "Chris Answood"}
user["name"]

>Solution :

In Swift, you can use a struct or class to create an object with properties, similar to an object literal in JavaScript. Here’s an example of creating an object with a "name" property in Swift:

struct User {
    let name: String
}

let user = User(name: "Chris Answood")
print(user.name) // Output: "Chris Answood"

You can also use a Dictionary in Swift, which is similar to a JavaScript object. Here is an example:

var user = ["name": "Chris Answood"]
print(user["name"]) // Output: Optional("Chris Answood")

Note that the value returned by the Dictionary is an Optional, you can use if let or guard let to unwrap the value.

Leave a Reply