[英]typecast userdefaults into Int() in swift
這里設定的價格為用戶默認( LoggedInUserSave
是參考UserDefault
):
let currentValue = Int(sender.value)
LblPriceValue.text = "\(currentValue)"
Price = "0," + String(describing: currentValue)
LoggedInUserSave.set(Price, forKey: "PriceFilter")
我需要將price
值用作Int
。 我正在使用此代碼將price
轉換為int
:
p = LoggedInUserSave.value(forKey: "PriceFilter") as! String
Price : Int = Int(p)!
在做這個事情的同時獲得零價值。
我注意到,您的代碼中存在幾個異常(不正確地使用了課程的命名約定),此行(設置值時)表示var Price
是String
類型
Price = "0," + String(describing: currentValue)
在此處(接收值時)設置的位置表示Price
為integer
。
現在解決您的問題,請確保:
sender.value
不為nil,僅包含數字字符(否則類型轉換將不會成功) "0," + String(describing: currentValue)
,它使string
文字無法再次轉換為Int
。 這將是實現您正在嘗試的方法的更合適的方法:
if let i = sender.value as? Int {
self.lbl.text = "\(i)"
UserDefaults.standard.set(i, forKey: "Key")
}
_
//..
if let i : Int = UserDefaults.standard.integer(forKey: "Key") {
//do what you want to do with stored value
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.