为什么我不能使用Swift打开该可选值?

时间:2018-06-26 17:26:29

标签: swift optional forced-unwrapping

我正在尝试获取第一条记录的值,即“ 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给我一个错误,说明您正试图解开无可选值。

知道我在哪里犯错吗?

3 个答案:

答案 0 :(得分: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 

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

答案 1 :(得分: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")
}

答案 2 :(得分: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])")