简体   繁体   中英

Converting Swift to F# - optionals and type casting

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")

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 -> ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM