繁体   English   中英

快速将用户默认类型转换为Int()

[英]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 PriceString类型

Price = "0," + String(describing: currentValue)

在此处(接收值时)设置的位置表示Priceinteger

现在解决您的问题,请确保:

  • 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM