如何避免这种强制施法

时间:2018-11-07 20:47:19

标签: swift nsuserdefaults

我认为我在应用中施加的强制力使其崩溃((userDefaults.value(forKey:“ timeDiffSecondsDefault”)as!Int?)...)但是我真的不知道如何避免。任何指导都将不胜感激!

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)

}

2 个答案:

答案 0 :(得分:1)

使用专用API,该API返回非可选

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

如果需要默认值!= 0 register


注意:除非确实需要KVC,否则不要将value(forKeyUserDefaults一起使用

答案 1 :(得分:0)

缺少密钥时,您尝试将空的Any?强制转换为Int?,因此,不执行if条件:

if let defaultTimeDiffSeconds: Int = userDefaults.value(forKey: "timeDiffSecondsDefault") as! Int? {
    timeDiffSeconds = defaultTimeDiffSeconds
}

如果timeDiffSeconds没有在其他地方初始化,则在尝试使用它时会导致崩溃。

适当的方法是使用as?进行条件转换:

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

object(forKey:)Mr Leonardo提出。

稍后使用userDefaults.integer(forKey: "timeDiffSecondsDefault")时使用timeDiffSeconds可能会造成混淆,因为如果用户默认值中不存在密钥,integer(forKey:)将返回0,即使值是字符串或布尔值。

相关问题