swiftswift-structs

Access swift structure attribute using a variable


I am new to swift and I am trying to find out, how to access the structure attribute through a variable. Being a JS developer, we are able to access the object key through a variable, so I am trying to find out if swift is also able to do the same?

//example in javascript
const someArray = [
   {key1: "value 1"},
]

const getValue1 = (key) => {
   return someArray[0][key]
}

//will return "value 1" 
getValue1(key1) 

so likewise, for swift I am trying to access the attribute within a dictionary of structure items. Story has been initiated as a struct.

let stories = [
  Story(
            title: "Some Title",
            choice1: "Choice 1",
            choice2: "Choice 2",
        )
]

 func getChoiceText(choice: String) -> String {
   // get the choice string based on choice parameter -> "choice1" || "choice2"
   // eg something like this -> return stories[0][choice] 
 }

// so that I can get the corresponding choice text by calling the function 
getChoiceText(choice: "choice1")

thank you for your help in advance!! :)


Solution

  • The closest equivalent in Swift is a generic function passing a key path

    func getValue<T>(path: KeyPath<Story,T>) -> T {
        return stories[0][keyPath: path]
    }
    

    and call it

    getValue(path: \.choice1)
    

    But be aware that the code crashes if stories is empty.