Reputation: 47
I am trying to get the value for first record which is "2018-05-04 09:00:00 +0000". When I print out `firstRecord', I get an optional value in the terminal:
optional(2018-05-04 09:00:00 +0000).
Then I tried to unwrap it like so:
if dailyArray.count == 0 {
print("no record was found")
}else{
guard let firstRecord : String = dailyArray[0]["startTime"] as! String else {return}
let firstRecordArray = firstRecord.components(separatedBy: " ")
print("data exist \(firstRecordArray[0])")
}
And now Xcode is giving me an error saying that you are trying to unwrap a none optional value.
Any idea where am I making a mistake?
Upvotes: 0
Views: 368
Reputation: 3571
You can use optional chaining and the if let syntax to unwrap the variable and make the code much more concise and clear:
// dailyArray should be declared as or typecast to [[String : String]]
guard !dailyArray.isEmpty else {
print("no record was found")
exit(1) // or return if in func
}
if let firstRecord = dailyArray.first?["startTime"]?.components(separatedBy: " ") {
print("data exists: \(firstRecord.first)")
}
else {
print("no start time date was found")
}
Upvotes: 0
Reputation: 63137
If you're going to use optional chaining, then you may as well use .first
(returns an optional, nil
on empty array) rather than [0]
(returns value, crashes on empty array):
guard !dailyArray.isEmpty else {
print("no record was found")
return
}
guard let firstRecord = dailyArray.first?["startTime"] as? String else {
return
}
let firstRecordArray = firstRecord.components(separatedBy: " ")
print("data exist \(firstRecordArray[0])")
Upvotes: 0
Reputation: 3708
Do like this
guard !dailyArray.isEmpty, let firstRecord = dailyArray[0]["startTime"] as? String else { return }
let firstRecordArray = firstRecord.components(separatedBy: " ")
print("data exist \(firstRecordArray[0])")
In your code you are typecasting forcely thatswhy
["startTime"] as! String
this means that the value is Strictly string while ? says it can be string
Upvotes: 1