Rorschach Rorschach - 5 months ago 15
Swift Question

Retrieving a value from an Optional

I am using xcode, making a swift application.

I have this optional value which I printed into the console using:

print(myData)


Here is the optional

Optional({
"avatar_content_type" = "image/png";
"avatar_file_name" = "add_a_photo_three-b04cdb4bcfc59b603590d88567e359115b3bbc63acfde789bd6f2caa3a1410ce.png";
"avatar_file_size" = 17312;
"avatar_updated_at" = "2016-05-24T22:36:17.000Z";
"cover_image_file_name" = "<null>";
"cover_image_url" = "/images/_staging/og-image-alt.png";
"created_at" = "2016-05-24T22:36:17.000Z";
creator = "<null>";
description = "";
id = 246;
"mycount" = 0;
name = "Spring/Summer";
size = 0;
"updated_at" = "2016-05-24T22:36:26.000Z";
user = {
"avatar_content_type" = "image/png";
"avatar_file_name" = "upload.png";
"avatar_file_size" = 5534390;
"avatar_updated_at" = "2015-12-26T22:07:02.000Z";
bio = "Chief";
"created_at" = "2015-11-09T02:20:42.000Z";
"date_of_birth" = "1982-07-29";
email = "person@site.com";
"first_name" = Joseph;
gender = male;
id = 3;
"is_private" = 0;
"last_name" = Romulus;
"next_stand_number" = "<null>";
"profile_image_medium_url" = "/images/users/original/3.png/?1451167622";
"profile_image_thumb_url" = "/images/users/thumb/3.png/?1451167622";
provider = "<null>";
uid = "<null>";
"updated_at" = "2016-06-09T18:38:47.000Z";
"user_name" = Joe;
"user_token" = "############";
};
"user_id" = 3;
})


I am trying to do this

let created_at_raw = data["created_at"] as! String


but it gives this error:

fatal error: unexpectedly found nil while unwrapping an Optional value


I am used to using Dictionaries, but this isnt one and I am confused on how to just get the value from here:
"created_at" = "2016-05-24T22:36:17.000Z";


EDIT 1

More code:

let created_at_raw = data["created_at"] as! String
let formatter : NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
formatter.timeZone = NSTimeZone(name: "UTC")
self.created_at = formatter.dateFromString(created_at_raw)!


EDIT 2

class MYUserStuff: MYObject {
private var created_at : NSDate

init(data: Dictionary<String, AnyObject>) {

...


if let created_at_raw = data["created_at"] as? String {
let formatter : NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
formatter.timeZone = NSTimeZone(name: "UTC")
self.created_at = formatter.dateFromString(created_at_raw)!
}
...

}


gives the error:

.swift:18:5: Property 'self.created_at' not initialized at implicitly generated super.init call

Answer

You have to unwrap it

if let created_at_raw = data["created_at"] as? String {
    // Use created_at_raw here :)
}