草庐IT

ios - swift 3 : What's the safest way to unwrap optional values coming from an array?

coder 2023-09-07 原文

首先,我初始化变量以保存股票数据

var applePrice: String?
var googlePrice: String?
var twitterPrice: String?
var teslaPrice: String?
var samsungPrice: String?
var stockPrices = [String]()

我从 YQL 中获取当前股票价格,并将这些值放入一个数组中

func stockFetcher() {

    Alamofire.request(stockUrl).responseJSON { (responseData) -> Void in
        if((responseData.result.value) != nil) {
            let json = JSON(responseData.result.value!)
            if let applePrice = json["query"]["results"]["quote"][0]["Ask"].string {
                print(applePrice)
                self.applePrice = applePrice
                self.tableView.reloadData()
            }
            if let googlePrice = json["query"]["results"]["quote"][1]["Ask"].string {
                print(googlePrice)
                self.googlePrice = googlePrice
                self.tableView.reloadData()
            }
            if let twitterPrice = json["query"]["results"]["quote"][2]["Ask"].string {
                print(twitterPrice)
                self.twitterPrice = twitterPrice
                self.tableView.reloadData()
            }
            if let teslaPrice = json["query"]["results"]["quote"][3]["Ask"].string {
                print(teslaPrice)
                self.teslaPrice = teslaPrice
                self.tableView.reloadData()
            }
            if let samsungPrice = json["query"]["results"]["quote"][4]["Ask"].string {
                print(samsungPrice)
                self.samsungPrice = samsungPrice
                self.tableView.reloadData()
            }
            let stockPrices = ["\(self.applePrice)", "\(self.googlePrice)", "\(self.twitterPrice)", "\(self.teslaPrice)", "\(self.samsungPrice)"]
            self.stockPrices = stockPrices
            print(json)
        }
    }
}

在 cellForRowAt indexPath 函数中我打印到标签

    if self.stockPrices.count > indexPath.row + 1 {
        cell.detailTextLabel?.text = "Current Stock Price: \(self.stockPrices[indexPath.row])" ?? "Fetching stock prices..."
    } else {
        cell.detailTextLabel?.text = "No data found"
    }

我遇到了打印 Current Stock Price: Optional("stock price") 和 optional 这个词的问题。我想这是因为我给了它一个可选值数组,但我有点不得不这样做,因为我实际上不知道是否会有来自 YQL 的数据,5 只股票中的一只可能是 nil 而其他人有数据。通过阅读其他类似的问题,我可以看到解决方案是用 ! 解包值,但是当它是一个包含可能是 的数据的数组时,我不太确定如何实现该解决方案>nil,而不只是一个 Int 或其他东西。

我怎样才能在这里安全地解包并去掉 Optional 这个词?

最佳答案

首先:

任何时候你多次重复同一个代码块并且只将一个值从 0 增加到某个最大值,这就是代码味道。您应该考虑一种不同的方式来处理它。

你应该使用一个数组来做这个处理。

索引的一组枚举怎么样:

enum companyIndexes: Int {
  case apple
  case google
  case twitter
  case tesla
  //etc...
}

现在你可以用一个循环遍历你的数组并更干净地安装你的值:

var stockPrices = [String?]()
Alamofire.request(stockUrl).responseJSON { (responseData) -> Void in
    if((responseData.result.value) != nil) {
        let json = JSON(responseData.result.value!)
        let pricesArray = json["query"]["results"]["quote"]
        for aPriceEntry in pricesArray {
           let priceString = aPriceEntry["ask"].string
           stockPrices.append(priceString)
        }
   }
}

并从数组中获取价格:

let applePrice = stockPrices[companyIndexes.apple.rawValue]

这将导致一个可选的。

您可以使用 nil 合并运算符 (??) 将 nil 值替换为类似“No price available”的字符串。

let applePrice = stockPrices[companyIndexes.apple.rawValue] ?? "No price available"

或如其他答案所示:

if let applePrice = stockPrices[companyIndexes.apple.rawValue] {
   //we got a valid price
} else
   //We don't have a price for that entry
}

关于ios - swift 3 : What's the safest way to unwrap optional values coming from an array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40939421/

有关ios - swift 3 : What's the safest way to unwrap optional values coming from an array?的更多相关文章

随机推荐