0

我正在尝试获取第一条记录的值,即“2018-05-04 09:00:00 +0000”。当我打印出 `firstRecord' 时,我在终端中得到一个可选值:

可选(2018-05-04 09:00:00 +0000)。

然后我试着像这样解开它:

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

现在 Xcode 给我一个错误,说你试图解开一个非可选值。

知道我在哪里犯错了吗?

4

3 回答 3

1

这样做

guard !dailyArray.isEmpty, let firstRecord = dailyArray[0]["startTime"] as? String else { return }
let firstRecordArray = firstRecord.components(separatedBy: " ")
print("data exist \(firstRecordArray[0])")

在您的代码中,您正在强制进行类型转换,这就是为什么

["startTime"] as! String 

这意味着该值是严格字符串,而? 说它可以是字符串

于 2018-06-26T17:30:10.027 回答
0

您可以使用可选链接和 if let 语法来解包变量并使代码更加简洁明了:

// 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")
}
于 2018-06-26T18:10:45.783 回答
0

如果您要使用可选链接,那么您也可以使用.first(返回一个可选的,nil在空数组上)而不是[0](返回值,在空数组上崩溃):

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])")
于 2018-06-26T18:22:23.320 回答