将UInt32值保存到NSUserDefaults(Swift 2.0)错误

我是Swift 2.0的新手,而且我已经相当坚持了......我根据用户设置范围创建了一个随机数生成器,用于低限制和高限制 . 当我可以将低和高变量设置为Uint32时,此函数对我的测试函数很有效 . 一旦我尝试将NSUserDefaults中的低/高范围存储为整数 . 现在,当我尝试加载用户设置的低值和高值以在我的函数中使用时,它给出了一个错误,它需要是一个UInt32值 .

问题是......我似乎无法弄清楚如何将它们保存在NSUser中作为该类型 . 或者将其打包为来自UserDefaults的那种类型 .

我的具体错误消息是... ERROR IS二进制运算符不能应用于UInt32和In类型的操作数

非常感谢您的帮助和时间,我真的很感激!你们这里真棒!

如果您需要我还有其他信息,请告诉我:)

//CREATE SAVE SETTINGS FOR LOW AND HIGH RANGE
 NSUserDefaults.standardUserDefaults().integerForKey("CatLowRange")                       
 NSUserDefaults.standardUserDefaults().integerForKey("CatHighRange")

//Variables to load in values from NSUserDefaults on load
var catLowRange             = 0     //Load In Low Range From NSUser
var catHighRange            = 40    //Load In High Range From NSUser

//LOAD IN VALUES TO VARIABLES FROM NSUSERDEFAULTS

catLowRange = NSUserDefaults.standardUserDefaults() . integerΔKey(“CatLowRange”)

catHighRange = NSUserDefaults.standardUserDefaults() . integerΔKey(“CatHighRange”)

**//My Function To Generate RandNumber...** 
*ERROR IS Binary Operator + cannot be applied to operands of type UInt32 and Int*
randomNumber = arc4random_uniform (catHighRange - catLowRange) + catLowRange

回答(2)

3 years ago

使用此代码(针对swift 3更新):

let number : UInt32 = 8

    UserDefaults.standard.set(NSNumber(value: number), forKey: "key")

    let number2 = (UserDefaults.standard.value(forKey: "key") as? NSNumber)?.uint32Value

3 years ago

对于任何想知道的人...感谢亚当,我们有一个答案...这里的代码分解了我如何使用他的建议使这件事工作:)

//WORKING METHOD!?
    //vars for use
    let catLowRange         : UInt32    = 0
    let catHighRange        : UInt32    = 40

    var randNumGenerated    : UInt32    = 0

    //SAVEPOINTS (STEP 1 - save the UInt32s as int for saving)
    NSUserDefaults.standardUserDefaults().setInteger(Int(catLowRange), forKey: "CatLowRange")
    NSUserDefaults.standardUserDefaults().setInteger(Int(catHighRange), forKey: "CatHighRange")

    //LOAD (STEP 2 - Take Int save as a UInt32 now)
    let catLowRangeLoad = UInt32(NSUserDefaults.standardUserDefaults().integerForKey("CatLowRange"))
    let catHighRangeLoad = UInt32(NSUserDefaults.standardUserDefaults().integerForKey("CatHighRange"))

    //FUNCTION TEST
    randNumGenerated = arc4random_uniform (catHighRangeLoad - catLowRangeLoad) + catLowRangeLoad

    //CHECK
    print ("catLowRange = \(catLowRange)")
    print ("catLowRangeLoad = \(catLowRangeLoad)")
    print ("catHighRange = \(catHighRange)")
    print ("catHighRangeLoad = \(catHighRangeLoad)")
    print ("randNumGen = \(randNumGenerated)")