How to avoid this Force Cast

1852 views swift

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 = .second, value: timeDiffSeconds, to: Date())!
    if store {
        storeDateComponents(nowProdTime: productionTime)
    productionTimeString = productionTimeFormatter.string(from: productionTime)
    liveCounterButton.setTitle(productionTimeString, for: .normal)


answered question

2 Answers


Replace with

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

posted this

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?


Please login first before posting an answer.