通过 Swift 编程访问二维数组中的值 [英] Access a value in a 2D array through programming in Swift

查看:31
本文介绍了通过 Swift 编程访问二维数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了 Aliment 结构.我有一个 Aliment 数组.

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

我如何获取第二种食物的卡路里值,我的意思是Pomme"的卡路里为 120 卡路里,但通过编程而不是直接访问.谢谢.

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.

推荐答案

可以使用下标方法(arrayProperty[index])访问数组的第二个元素,注意第一个元素在您的情况下,索引为 0:

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

此外,我建议遵循 swift 命名约定,这意味着属性 ListAlimentsBrut 应以小写开头,并在不说明数据类型的情况下命名属性(此处列出)并保持语言之间的一致性(仅英语,而不是法语和英语的混合),例如:

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 = [...]

这篇关于通过 Swift 编程访问二维数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆