簡體   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