【问题标题】:Use of Array in a Struct in Swift在 Swift 的结构中使用数组
【发布时间】:2020-08-17 09:37:47
【问题描述】:

我有以下结构,其中我使用字符串、Int 和 Bool。当我从 Firestore 查询我的产品时,我会填写这些变量。现在我不知道如何在我的结构中处理数组:

struct Product {
    var price: Int
    var name: String
    var isActive: Bool
    //var categories: how do I call out the array here?
init(
        price: Int,
        name: String,
        isActive: Bool,
        //categories: how do I call out the array here?
        ){
        self.price = price
        self.name = name
        self.isActive = isActive
        //self.categories: how do I call out the array here?
    }

    init(data: [String: Any]){
        price = data[DatabaseRef.price] as? Int ?? 0
        name = data[DatabaseRef.name] as? String ?? ""
        isActive = data[DatabaseRef.isActive] as? Bool ?? false
        //categories: how do I call out the array here?
    }

static func modelToData(product: Product) -> [String: Any] {

        let data : [String: Any] = [
            DatabaseRef.price : product.price,
            DatabaseRef.name : product.name,
            DatabaseRef.isActive : product.isActive,
           //categories: how do I call out the array here?
       ]
        return data
    }
}

当我从我的数据库中查询我的类别时;它看起来像这样:

categories = ["Fruits", "Vegetables", "Frozen"]

不确定如何在我在这里提到的结构的每个部分中调用类别。新手警告!

【问题讨论】:

  • 只需声明[String]类型的属性
  • 有道理;这条线怎么样? category = data[DatabaseRef.category] as? [String] ?? [ ]你是这样声明的吗?

标签: ios arrays swift xcode struct


【解决方案1】:

你可以像这样声明一个数组。

var 类别:[String] = []

【讨论】:

    猜你喜欢
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    相关资源
    最近更新 更多