I am trying to use values from my WordPress server in my Swift project. I get the information in JSON format. The values that I want is created by “advanced custom fields” on the wordpress server.
I am loading it from another view controller and use this code to load it:
let nummer = NSUserDefaults.standardUserDefaults().valueForKey("nummer")
print(nummer)
Then I get this result:
{
attachments = (
);
author = {
description = "";
"first_name" = "";
id = 1;
"last_name" = "";
name = admin;
nickname = admin;
slug = admin;
url = "";
};
categories = (
);
"comment_count" = 0;
"comment_status" = open;
comments = (
);
content = "<p>text</p>n";
"custom_fields" = {
latitude = (
"22.324432"
);
longitude = (
"40.233221"
);
};
date = "2015-12-11 08:12:31";
excerpt = "<p>text</p>n";
id = 37;
modified = "2015-12-11 08:12:31";
slug = "test-2";
status = publish;
tags = (
);
title = test;
"title_plain" = test;
type = post;
url = "http://localhost:8080/wordpress/2015/12/11/test-2/";
}
To get the title I use this code:
let dict = nummer!["title"] as? String
print(dict)
And get this result:
Optional(“test”)
I use this code to get longitude value:
let dict = nummer!["custom_fields"]
let longitude = dict!!["longitude"]
print(longitude)
Result:
Optional((
“40.233221”
))
Now I want to convert it to a double. But it returns nil:
let longitude = dict!!["longitude"] as? Double
print(longitude)
Result: nil
Why does it returns nil and not the double value?
When you use
as?
you are attempting to downcast the unwrapped value to aDouble
, but it isn’t aDouble
it’s anArray
.Because this variable is a
String
notDouble
. You have to convert itor