0

我是 swift 新手,我正在尝试找出如何通过变量访问结构属性。作为一名 JS 开发人员,我们可以通过变量访问对象键,所以我想知道 swift 是否也能做到这一点?

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

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

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

同样,为了快速,我试图访问结构项字典中的属性。故事已作为结构启动。

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

提前谢谢你的帮助!!:)

4

1 回答 1

0

Swift 中最接近的等价物是传递关键路径的泛型函数

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

并称之为

getValue(path: \.choice1)

但请注意,如果stories为空,代码会崩溃。

于 2022-02-03T05:38:56.280 回答