1

I know the below is possible in Javascript. Is there anything similar I can use in SwiftUI to pass an object property as a String?

var a = { foo: 123 };
a.foo    // 123
a['foo'] // 123
var str = 'foo';
a[str]   // 123
4
  • 1
    I think you can use dictionaries Commented Jun 3, 2021 at 19:30
  • 1
    var a = { foo: 123 }; and a.foo are like a class/struct. a['foo'] and a[str] look like dictionaries. Commented Jun 3, 2021 at 19:37
  • How would you use this in Swift? Can you give us some usage examples of you you'd want to use this feature? Commented Jun 3, 2021 at 19:52
  • Where is the SwiftUI in this question? Commented Jun 6, 2021 at 19:13

1 Answer 1

1

What you likely want here is a key path. For example, given:

struct A {
    var foo: Int
}

You can construct an A, and access it:

let a = A(foo: 123)
a.foo // 123

And given that, you can access the foo property by key path:

let kp = \A.foo
a[keyPath: kp]  // 123

If your actual goal is to map strings to integer, that's just a [String: Int], and it would work identically. If you mean "I want to pass strings to objects has have fairly random things happen, and possibly crash like they do in JavaScript," then that's also possible, using a custom subscript like subscript(key: String) -> Int?.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.