Reputation: 5557
I'm trying to convert the following Swift
code into F#
:
if let type : String = UserDefaults.standard.object(forKey: "type") as? String {
if (type == "this") {
} else if (type == "that") {
}
}
I came up with this, however I'm not sure how to cast the value to a String
and store it in a variable, as all this code does is checks if the value is not null.
if NSUserDefaults.StandardUserDefaults.ValueForKey(new NSString("type")) <> null then printf("fofo")
Upvotes: 1
Views: 109
Reputation: 19897
In F#, you can do casting using either the :>
operator (if the cast is an upcast) or the :?>
operator if the cast is a downcast. It would look something like this:
let objObject= "test" :> obj
let strObject = objObject:?> string;;
val objObject: obj = "test"
val strObject : string = "test"
Converting your use defaults would look something like this:
let strValue = NSUserDefaults.StandardUserDefaults.ValueForKey(new NSString("type")) :?> string
If you want to check for multiple types, then you'll probably want to use pattern matching like this:
let strObject = match objObject with
| :? string as strObject -> strObject
| :? System.Int32 as intObject -> ""
Upvotes: 1