从任何类型转换为特定类型

时间:2018-11-02 20:46:01

标签: ios swift firebase google-cloud-firestore

我有firestore数据库“ sales”,其中有一列称为saleapproveddate。有2个级别的人员,一个记录销售记录,另一人批准销售记录。在记录销售时,我将saleapproveddate另存为NSNull()(在firestore DB字段中另存为nil)。批准者可以将saleapproveddate更新为TimeStamp,但是如果批准者从未批准销售日志,则在Firestore DB字段中仍保留为nil。因此它可以具有nilTimeStamp类型。

我有销售模型

class Sale  {

    var saleapprovedate : Any?
}

当我从Firestore加载数据时,我尝试将saleapprovedate下调为Any

let approvedDate = document[SaleProperties.paidDate.rawValue] as Any

但是真正的挑战是,saleapprovedate可以有nilTimestamp。如何检查类型条件,转换为特定类型并显示在标签中?

以下是我尝试过的内容:

While loading data:
sale.saleapprovedate = document[SaleProperties.saleapprovedate.rawValue] as Any

while displaying data:
let saleItem = sales[indexPath.row]
let paidDate = saleItem.saleapprovedate
if paidDate == nil {
            cell.paidDateLabelContainer.text = "Yet to pay"
            cell.paidStatusImageView.isHidden = true
        }

        else  {
            let paidDateTimeStamp = saleItem.saleapprovedate as! Timestamp
           let convertedPaidDate = self.convertTimestampToDate(timeStamp: paidDateTimeStamp)
            cell.paidDateLabelContainer.text = convertDateToString(date: convertedPaidDate)
            cell.paidStatusImageView.isHidden = false

        }

但是上面的代码无法正确更新单元格标签。我有两个数据,一个具有saleapprovedate作为Timestamp,另一个具有nil。两个单元格标签都显示为“还需付款”。怎么了?

1 个答案:

答案 0 :(得分:0)

Modal :
var incentivepaiddate : Any?

Array :
var sales : [Sale] = [Sale]()

Loading data from firestore :

for document in querySnapshot!.documents {
let sale = Sale()
sale.incentivepaiddate = document[SaleProperties.incentivepaiddate.rawValue]
self.sales.append(sale)
}

检查是否为零,向下转换为特定类型并在单元格中显示数据

let saleItem = sales[indexPath.row]
let paidDate = saleItem.incentivepaiddate

 if let paid = paidDate {

            let paidDateTimeStamp = paid as? Timestamp
            let convertedPaidDate = self.convertTimestampToDate(timeStamp: paidDateTimeStamp!)
            cell.paidDateLabelContainer.text = convertDateToString(date: convertedPaidDate)
        }
        else {
            cell.paidDateLabelContainer.text = "Yet to pay"
            cell.paidStatusImageView.isHidden = true
        }

希望这对某人有帮助!