Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading