我正在学习如何访问struc中的属性。我正在尝试从categorie结构访问title属性。我只能进行business.categories。如何访问标题属性。
struct categorie: Decodable{
let title: [String]
}
struct Business: Decodable {
let name: String = ""
let categories: [categorie]
}
答案 0 :(得分:0)
第一件事是第一位。让我们修复您的结构名称。 struct
声明应为CapitalizedCamelCase
,因此您的结构如下所示:
struct Categorie: Decodable{
let title: [String]
}
struct Business: Decodable {
let name: String = ""
let categories: [Categorie]
}
接下来,您要在categories
数组中查找元素的title属性,因此您可以这样做:
business.categories[0].title
您需要指定要检查的数组元素。在上面的示例中,我获得了第一个元素的([0]
)title
属性。您需要添加一些逻辑以防止类别为空。