【发布时间】:2016-12-02 19:13:59
【问题描述】:
首先,我初始化变量以保存股票数据
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"
}
我遇到了打印当前股票价格的问题:可选(“股票价格”),带有可选的单词。我认为这是因为我给它一个可选值数组,但我有点不得不这样做,因为我实际上不知道是否会有来自 YQL 的数据,5 支股票中的一支可能是nil 而其他人有数据。通过阅读其他类似的问题,我可以看到解决方案是用! 解开值,但是当它是一个包含可能是nil 的数据的数组时,我不太确定如何实现该解决方案,而不仅仅是一个 Int 什么的。
我怎样才能在这里安全地打开包装并去掉 Optional 这个词?
【问题讨论】:
-
不要添加使用字符串插值将数据添加到您的数组中;只需直接添加字符串(即
[self.applePrice, self.googlePrice,...]但邓肯的做法是正确的