Handling null value in a dictionary object - swift3

I am using a web service to get information. When said info is returned, I convert the data received from jason to a dict.
When Dumping dict object, some of the items arrive like this:
▿ (2 elements)
- key: "street1"
- value: <null> #4
How would i go about reading this data and knowing that the value is NULL
I have tried the following:
let street1:String = dict?["street1"] as! String
This fails with: Could not cast value of type 'NSNull' (0x10fbf7918) to 'NSString' (0x10f202c60).
The data could have a String value. So I tried:
let street1:Any = dict?["street1"] as Any
When I print street1 thus
street1: Optional()
I get the following
street1: Optional()
So my question is:
How would i go about reading this data and knowing that the value is null.

You can use if let for this type of nil check.
Try this instead:
if let street1 = dict?["street1"] as? String {
// If this succeeds then you can use street1 in here
print(street1)
}
Update:
var t_street1 = ""
if let street1 = dict?["street1"] as? String {
t_street1 = street1
}
No need for the else t_street1 is automatically empty since you assign it empty.

Related

Dynamically referring to JSON node in Power Query M

I have a function that extracts a node from JSON document as follows:
...
Json = GetJson(Url),
Value = Json[#"values"]
values correspond to the actual node within the JSON document.
I would like to generalize this piece of code and provide the name of the node as a variable like:
let myFunc = (parentNodeName as text) =>
...
Json = GetJson(Url),
Value = Json[parentNodeName]
However getting this error:
An error occurred in the ‘myFunc’ query. Expression.Error: The field 'parentNodeName' of the record wasn't found.
How can I refer to the JSON node dynamically?
Try
(Json, parentNodeName ) =>
let
...
Value = Record.Field(Json,parentNodeName)
in Value
sample code:
let Json = Json.Document(Web.Contents("http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json")),
Value=myFunc(Json,"title")
in Value
and myFunc:
(Json, parentNodeName ) =>
let
Value = Record.Field(Json,parentNodeName)
in Value

Extract String value from Node

I'm trying to query a database using something like this:
let db = drop.database?.driver as? MySQLDriver
let query = "select \(fields) from \(table) where \(condition)"
let result = try db.raw(query)
I get the following Node object as result:
array([Node.Node.object(["field_name": Node.Node.string("value_info")])])
How can I get the value_info into a String variable?
You can use PathIndexable to step into the result object, then Polymorphic to cast it as a string.
Should look something like this:
let valueInfo = result[0, "field_name"]?.string

Type Any? has no subscript members on NSDictonary iOS

I am trying to change my code to swift 2.1 to swift 3
but I am getting following error :
Type Any? has no subscript members
Earlier I was using
let activityCount = self.activityCoutArray.value(forKey: "ActivitytodoCount")[0].value(forKey: "Count") as! Int
and I have changed to Swift 3
let activityCount = self.activityCoutArray["ActivitytodoCount"][0]["Count"] as? [String:Any]
but still it is giving same error ,
Please help me where I am going wrong..
It should be like this. First get array of dictionary([[String:Any]]) and then access the first element from array after that get the value from Dictionary that you want.
if let activityArray = self.activityCoutArray["ActivitytodoCount"] as? [[String:Any]],
let firstDic = activityArray.first, let count = firstDic["count"] as? Int {
print(count)
}

Label displaying "Optional('#') in Swift when using NumberFormatter

I have the following code:
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
numberFormatter.maximumFractionDigits = 2
let formattedNumber = numberFormatter.string(from: NSNumber(value: rawValue))
currentLogBF.text = "\(formattedNumber) BF"
In the above example, rawValue is a Double that is calculated when all of the input fields have values in them.
currentLogBF is a label in my View.
Whenever a calculation is completed, the label displays something like this:
Optional("12,307.01") BF
How do I get rid of the "Optional()" piece, so it just displays this:
12,307.01 BF
Any ideas what I am doing wrong here?
The function numberFormatter.string(from: NSNumber) will return you a String Optional (String?) instead of String.
You will need to unwrap it first like this
if let formattedNumber = numberFormatter.string(from: NSNumber(value: rawValue)) {
currentLogBF.text = "\(formattedNumber) BF"
} else {
Log.warn("Failed to format number!")
}
And as bonus, use String(format: "%# BF", formattedNumber) rather than "\(formattedNumber) BF" when dealing with optional.
String(format:) will give you compile error when you try to pass optional value as an argument
unwrapping an optional value
let formattedNumber:String? = numberFormatter.string(from: NSNumber(value: rawValue))
currentLogBF.text = "\(formattedNumber!) BF" //optional string. This will result in nil while unwrapping an optional value if value is not initialized or if initialized to nil.
currentLogBF.text = "\(formattedNumber) BF" //Optional("optional string") //nil values are handled in this statement

marshalling a hash table in ocaml

I have a hash table in ocaml and I want to store this entire hash table as value field in a Berkeley DB. So I am trying to Marshal the hash table using Marshal.to_string. This returns a string but when I try to unmarshal the same string using Marshal.from_string, an Exception is thrown.
Any ideas on what the issue here is?
You have to annotate the type of the value you're unmarshaling. Like so (in top-level):
type t = (string, string) Hashtbl.t;;
let key = "key" in
let t_original : t = Hashtbl.create 1 in
Hashtbl.add t_original key "value";
let t_marshalled = Marshal.to_string t_original [] in
let t_unmarshalled : t = Marshal.from_string t_marshalled 0 in
assert ((Hashtbl.find t_original key) = (Hashtbl.find t_unmarshalled key));;