2017-09-16 46 views
0

这里设置的价格为用户默认(LoggedInUserSave是参考UserDefault):类型转换成userdefaults INT()在迅速

let currentValue = Int(sender.value) 
LblPriceValue.text = "\(currentValue)" 
Price = "0," + String(describing: currentValue) 
LoggedInUserSave.set(Price, forKey: "PriceFilter") 

我需要使用priceInt。我使用这个代码转换的priceint

p = LoggedInUserSave.value(forKey: "PriceFilter") as! String 
Price : Int = Int(p)! 

虽然做这件事情让零值。

+0

对不起,什么是'价格:INT = INT(P)'!?我甚至无法编译。 – GreatBigBore

+0

价格只是变量来存储p的价值 – m123

+0

好,但我在谈论这种语法。我不知道它是什么意思,也不会编译。如果您发布了您使用的实际代码,则可以获得更好的质量帮助。 – GreatBigBore

回答

0

有几种异常情况(不包括错误使用命名的课程公约)在你的代码,因为我可以看到,这条线(当设置值)描绘了VAR Price是一种String

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

凡为这里(当收到价值时)你设置为Priceinteger

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

  • sender.value不是零,只包含数字字符(否则强制类型转换将不会成功)
  • 现在同时节省你喜欢"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 
    } 
+0

它给这样的错误无法将类型'NSTaggedPointerString'(0x10d978d60)的值转换为'NSNumber'(0x10e94d4a8)。 – m123

+1

不要使用'value(forKey:)'方法从UserDefaults读取值。要得到一个'Int',使用'integer(forKey:)'。 – rmaddy

+0

'integer(forKey:)'不返回可选项。 – rmaddy