由于swift 3.0中的可选字符串而崩溃

时间:2017-02-23 06:50:17

标签: swift

我正在将时间戳转换为时间,但我的timeStampToDate正在提供此输出"可选(1476775542548)"因为它崩溃了。所以我怎么能删除这个可选字符串。

    let timeStampToDate = (String(describing:merchant.post["timestamp"])) as String
    let timeSt = Date(jsonDate:"/Date(\(timeStampToDate))/")
    merchantOpenLbl.text = Date().onlyTimee(date: timeSt!)

    init?(jsonDate: String) {
    //        "/Date(1487058855745)/"

    let prefix = "/Date("
    let suffix = ")/"
    let scanner = Scanner(string: jsonDate)

    // Check prefix:
    guard scanner.scanString(prefix, into: nil)  else { return nil }

    // Read milliseconds part:
    var milliseconds : Int64 = 0
    guard scanner.scanInt64(&milliseconds) else { return nil }
    // Milliseconds to seconds:
    var timeStamp = TimeInterval(milliseconds)/1000.0

    // Read optional timezone part:
    var timeZoneOffset : Int = 0
    if scanner.scanInt(&timeZoneOffset) {
        let hours = timeZoneOffset / 100
        let minutes = timeZoneOffset % 100
        // Adjust timestamp according to timezone:
        timeStamp += TimeInterval(3600 * hours + 60 * minutes)
    }

    // Check suffix:
    guard scanner.scanString(suffix, into: nil) else { return nil }

    // Success! Create NSDate and return.
    self.init(timeIntervalSince1970: timeStamp)
} 

3 个答案:

答案 0 :(得分:3)

包含您从('')获得的可选值。

merchant.post["timestamp"]

注意:如果它仍然不起作用,那么您需要向我们展示if let timeStampToDate = merchant.post["timestamp"] as? String { print(timeStampToDate) let timeSt = Date(jsonDate:"/Date(\(timeStampToDate)))/") merchantOpenLbl.text = Date().onlyTimee(date: timeSt!) } 的声明

编辑:如果不是字符串,请尝试这样

Date(jsonDate:)

答案 1 :(得分:2)

您可以使用guard let来包装可选值。用以下代码替换您的代码。

guard let timeStampToDate = merchant.post["timestamp"] as? String else {
  return
}

let timeSt = Date(jsonDate:"/Date(\(timeStampToDate))/")
merchantOpenLbl.text = Date().onlyTimee(date: timeSt!)

答案 2 :(得分:0)

let timeStampToDate = (String(describing:merchant.post["timestamp"])) as String
let timeSt = Date(jsonDate:"/Date(\(timeStampToDate!))/")
merchantOpenLbl.text = Date().onlyTimee(date: timeSt!)

编辑

if let timeStampToDate = (String(describing:merchant.post["timestamp"])) as? String {
    let timeSt = Date(jsonDate:"/Date(\(timeStampToDate))/")
    merchantOpenLbl.text = Date().onlyTimee(date: timeSt!)
}