How to avoid this Force Cast

1852 views swift
8

I think that a force cast I have in my app is causing it to crash, (userDefaults.value(forKey: "timeDiffSecondsDefault") as! Int?)...but I really don't know how to avoid it. Any guidance is greatly appreciated!

    func getProductionTime(store: Bool = false) {

    let userDefaults = UserDefaults.standard

    let productionTimeFormatter = DateFormatter()
    productionTimeFormatter.timeZone = TimeZone(abbreviation: defaultTimeZone)
    productionTimeFormatter.dateFormat = defaultTimeFormat

    if let defaultTimeDiffSeconds: Int = userDefaults.value(forKey: "timeDiffSecondsDefault") as! Int? {
        timeDiffSeconds = defaultTimeDiffSeconds
    }
    let productionTime = Calendar.current.date(byAdding: .second, value: timeDiffSeconds, to: Date())!
    if store {
        storeDateComponents(nowProdTime: productionTime)
    }
    productionTimeString = productionTimeFormatter.string(from: productionTime)
    liveCounterButton.setTitle(productionTimeString, for: .normal)

}

answered question

2 Answers

2

Replace with

if let defaultTimeDiffSeconds = userDefaults.integer(forKey: "timeDiffSecondsDefault") as? Int {
  ///
}

posted this
2

Use the dedicated API which returns a non-optional

timeDiffSeconds = userDefaults.integer(forKey: "timeDiffSecondsDefault")

Never use value(forKey with UserDefaults

posted this

Have an answer?

JD

Please login first before posting an answer.