简体   繁体   中英

set value of UISlider with a variable

I have now spent about 12 hours trying to solve this riddle, but I just can't! The truth is I am about 3 weeks into my Swift adventure and this is the first time I have ever written any code (well I think I made a rainbow once on my Atari 800XL!)

I don't really know what I am doing.... I also understand that what I am trying to do here could be fundamentally wrong, and so I will appreciate gift wrapped criticism.

I have a slider - C1

I want to set its value with a variable. However, it wants a float and I can't seem to convert the array I am using to a float. In fact I can't get any of the array values to convert to anything else, and keep getting an error about AnyObject. The code below is one iteration of the trials i have run, all without any luck. It is driving me mad!

The errors are

can't assign a value of int to a value of type float AnyObject is not convertible to NSNumber; did you mean to use as! to force downcast

This is the code where I get the array from Parse and assign it to NSUSER.

        var defaults = NSUserDefaults.standardUserDefaults()

        var getAuditId:String = defaults.stringForKey("auditIdGlobal")!
        var userId:String = defaults.stringForKey("userIdGlobal")!

        var query = PFQuery(className: "auditData")
        query.whereKey("auditId", equalTo:getAuditId)
        query.findObjectsInBackgroundWithBlock {
            (objects: Array?, idError: NSError?) -> Void in

            if idError == nil {

                if let objects = objects as? [PFObject] {
                    for object in objects {


                        var auditId: AnyObject? = object["auditId"]!
                        var callEhs: AnyObject? = object["ehsData"]!
             NSUserDefaults.standardUserDefaults().setObject(callEhs, forKey: "ehsLoad")

This is the code at the user end

        var defaults = NSUserDefaults.standardUserDefaults()

        var loadArray = defaults.arrayForKey("ehsLoad")!

        var test: AnyObject = loadArray[0]

        var testFloat = Int(test)

        c1.value = testFloat

I appreciate that it shows an int above, but I can't convert to anything! Xcode asked me to insert a forced downcast to as!NSNumber

         var = int(test as! NSNumber)

here I get this error

Could not cast value of type '__NSCFString' (0x10c0bfc50) to 'NSNumber' (0x10c550b88). (lldb)

if I try to use a forced downcast

         var testFloat = test as! Float

On running the app i get the error

Could not cast value of type '__NSCFString' (0x10b690c50) to 'NSNumber' (0x10bb21b88). (lldb)

Your test variable is a NSString . Try

var test = loadArray[0] as! NSString

and then use

test.floatValue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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