Swift 3: What is the safest way to expand additional values ​​from an array?

First, I initialize the variables to store the stock data.

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

I extract the current stock prices from YQL and put these values ​​in an array

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)
        }
    }
}

in function cellForRowAt indexPath I type on the label

    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 - .

?

+4
3

:

, 0 max, . .

.

:

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
}
+3

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"
}
0

For safe deployment, use this code:

if let currentStockPrice = self.stockPrices[indexPath.row]
{
    // currentStockPrice available there
}
// currentStockPrice unavailable

If you need to expand several variables in one, if after another it can lead to unreadable code. In this case, use this template.

guard let currentStockPrice = self.stockPrices[indexPath.row]
else
{
    // currentStockPrice is unavailable there
    // must escape via return, continue, break etc.
}
// currentStockPrice is available
0
source

Source: https://habr.com/ru/post/1662680/


All Articles