Home > Mobile >  How to get a property of a tuple with a string?
How to get a property of a tuple with a string?

Time:01-19

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

CodePudding user response:

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.

CodePudding user response:

JavaScript doesn't have built-in tuple support. You just created an object and get the value of the name property inside this object. You have used user["name"] but user.name would also be possible.

To achieve this in Swift you can create a struct:

struct User {
    name: String
}

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

Unlike JavaScript, Swift has support for tuples. This is an easy example:

let user = (firstName: "Chris", lastName: "Answood")
print(user.firstName)
  • Related