Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift ! does not remove Optional()

Before, I have successfully added a ! to force an unwrap to remove the "Optional()" from a variable. I am unable to do this in data returned from Parse.com

    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]!, error: NSError!) -> Void in
        if error == nil {

            for object in objects {
                println(object[myObject]!)
            }

        } else {
            println("Error: \(error) \(error.userInfo!)")
        }

    }

In the example above, the entire table from the Parse.com class is returned and printed to the console. However,

Optional(...)

is returned for each line even though I force an unwrap using ! at the end

What am I missing?

(Note: myObject is the name of the Column in the Parse Class database)

like image 795
AppDever Avatar asked Dec 15 '14 22:12

AppDever


People also ask

How do I get rid of optional in Swift?

If my assumption is incorrect, then one quick hack you can quickly do to get rid of the "Optional" in the text is to change your strings to force unwrap item , like so: theYears. text = "\(item!. experience)" . Though I would recommend structuring things so that you're not force unwrapping with the !

How do you declare an optional variable in Swift?

How to declare an Optional? You can simply represent a Data type as Optional by appending ! or ? to the Type . If an optional contains a value in it, it returns value as Optional<Value> , if not it returns nil .

What will happen if you try to unwrap an optional that contains nil like so?

Unwrap an optional type with the nil coalescing operator If a nil value is found when an optional value is unwrapped, an additional default value is supplied which will be used instead. You can also write default values in terms of objects.

What is an optional value?

An optional value either contains a value or contains nil to indicate that the value is missing.


2 Answers

MirekE was right. It was a nested Optional(Optional()).

to fix I:

println(object[myObject]!!)
like image 73
AppDever Avatar answered Sep 21 '22 17:09

AppDever


You only have to put "!" at the end of your variable, in print area

self.addressLabel.text = "\(subThoroughfare) \(p.thoroughfare!) \n \(p.subLocality!) \n \(p.subAdministrativeArea!) \n)".
like image 34
walter Avatar answered Sep 21 '22 17:09

walter