Access a value in a 2D array through programming in Swift

孤人 提交于 2021-02-11 12:49:00

问题


I create Aliment struct. And i have an array of Aliment.

struct Aliment {
    let name: String
    let vitamineARetinol: Float
    let vitaminC: Float
    let vitaminD: Float
    let calories: Float
    let grammage: Float
}

let ListAlimentsBrut = [
    Aliment(name: "Orange", vitamineARetinol: 0.5, vitaminC: 57, vitaminD: 0.98, calories: 140, grammage: 100),
    Aliment(name: "Pomme", vitamineARetinol: 0.2, vitaminC: 6.25, vitaminD: 0.38, calories: 120, grammage: 100),
    Aliment(name: "Poire", vitamineARetinol: 0.1, vitaminC: 4.62, vitaminD: 0.58, calories: 140, grammage: 100),
    Aliment(name: "Laitue", vitamineARetinol: 0.3, vitaminC: 4.72, vitaminD: 0.92, calories: 105, grammage: 100),
    Aliment(name: "Laitue", vitamineARetinol: 0.7, vitaminC: 4.72, vitaminD: 0.63, calories: 122, grammage: 100),
    Aliment(name: "Poivron Jaune", vitamineARetinol: 0, vitaminC: 184, vitaminD: 0, calories: 29.2, grammage: 100)
]

how can i access the calorie value of the second food, i mean 120 calories for "Pomme", but through programming and not directly. Thank you.


回答1:


You can access the second element of the an array using the subscript method (arrayProperty[index]), note that the first element has an index of 0, in your case :

ListAlimentsBrut[1].calories

Also, I would recommend to follow the naming convention in swift meaning that the property ListAlimentsBrut should start with a lower case and to name the property without saying the type of the data (here list)and keeping consistency between language (just english, not a mix of french and english) like that for exemple :

let rawIngredients = [...]


来源:https://stackoverflow.com/questions/63357843/access-a-value-in-a-2d-array-through-programming-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!