As David said, I'd avoid force unwrapping and force casting.
But instead of an if let
statement, I'd rather use a guard let
in order to avoid the pyramid of doom, like this:
guard let srt = self.Coin[indexPath.row] as? [String:Any], let barr = srt["Price"] as? [[String:Any]], let sr2 = barr.first as? [String:Any] else {
print("Price is empty")
//Need to return, throw or whatever
}
And we can even remove your intermediate variables, but it's much less readable, like so:
guard let sr2 = ((self.Coin[indexPath.row] as? [String : Any])?["Price"] as? [[String : Any]])?.first as? [String : Any] else {
print("Price is empty")
//Need to return, throw or whatever
}
If you'd rather go with the if let
statement (in case you don't want to return or throw in your guard
statement's else
clause) you can also do it with a single if
statement, like that
if let srt = self.Coin[indexPath.row] as? [String:Any], let barr = srt["Price"] as? [[String:Any]], let sr2 = barr.first {
//Do something with sr2
}
And a shorter version without intermediate variables:
if let sr2 = ((self.Coin[indexPath.row] as? [String:Any])?["Price"] as? [[String:Any]])?.first {
//Do something with sr2
}
Whatever you choose... Don't force unwrap. Don't force try. Don't force cast. It will come back to bite you some day.