简体   繁体   中英

Facebook API Objective-C to Swift

I am trying to maken an app with some FB functionalities. I want to use some code from their examples, but I got stuck on the following:

First I create a string format, like so:

let userIDKeyFormat: String = "UserID%li"

I want to use this userIDKeyFormat to get a value from user defaults:

func getUserIDInSlot(slot: Int) -> String? {
    self.validateSlotNumber(slot)

    var key = String(format: userIDKeyFormat, slot)
    var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

    return defaults.objectForKey(key)
}

Xcode gives me an error on the return line, stating "AnyObject is not identical to String".

Could anyone help me please?

Thanks!

defaults.objectForKey(key) can be a NSData , NSString , NSNumber , NSDate , NSArray , NSDictionary , or nil

You have to explicitly cast it:

func getUserIDInSlot(slot: Int) -> String? {

    ...

    return defaults.objectForKey(key) as? String
}

With this, the function returns the String value only if defaults.objectForKey(key) is a NSString , otherwise nil .

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