Niels
Niels

Reputation: 125

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!

Upvotes: 0

Views: 44

Answers (1)

rintaro
rintaro

Reputation: 51911

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.

Upvotes: 1

Related Questions