[英]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.