[英]Swift 3: What's the safest way to unwrap optional values coming from an array?
首先,我初始化變量以保存庫存數據
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的數據,所以我不得不這樣做,五只股票中的一只可能nil
而其他股票則nil
有數據。 通過閱讀其他類似的問題,我可以看到解決方案是用!
來包裝值!
,但是當它是一個數據數組可能為nil
,而不僅僅是Int或其他東西時,我不確定如何實現該解決方案。
我如何在這里安全地打開包裝並擺脫“可選”一詞?
首先:
每當您多次重復相同的代碼塊並且僅將值從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值替換為“無價格”之類的字符串:
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
}
我正在Xcode之外編寫此代碼(因此可能會有輸入錯誤),但是這種邏輯應該可以工作。
if self.stockPrices.count > indexPath.row + 1 {
var txt = "Fetching stock prices..."
if let price = self.stockPrices[indexPath.row] {
txt = price
}
cell.detailTextLabel?.text = txt
} else {
cell.detailTextLabel?.text = "No data found"
}
為了安全解包,請使用該代碼:
if let currentStockPrice = self.stockPrices[indexPath.row]
{
// currentStockPrice available there
}
// currentStockPrice unavailable
如果您需要一個接一個地解開多個變量,則可能導致代碼無法讀取。 在這種情況下,請使用此模式
guard let currentStockPrice = self.stockPrices[indexPath.row]
else
{
// currentStockPrice is unavailable there
// must escape via return, continue, break etc.
}
// currentStockPrice is available
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.