noobdev
noobdev

Reputation: 417

Swift 2: AnyObject? is not convertible to NSString

I'm trying to check for an existing login using session but I was thrown this error

'AnyObject?' is not convertible to 'NSString'; did you mean to use 'as!' to force downcast?

at this line of code

self.usernameLabel.text = prefs.valueForKey("USERNAME") as NSString

The full code block is this

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var usernameLabel: UILabel!

//Check for existing login, else show login
override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)

    let prefs: NSUserDefaults = NSUserDefaults.standardUserDefaults()
    let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
    if (isLoggedIn != 1) {
        self.performSegueWithIdentifier("goToLogin", sender: self)
    } else {
        self.usernameLabel.text = prefs.valueForKey("USERNAME") as NSString
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

What is the best way to fix it?

Error thrown

Upvotes: 3

Views: 1214

Answers (2)

Iyyappan Ravi
Iyyappan Ravi

Reputation: 3245

change NSString to String,

self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String

its working fine, hope its helpful

Upvotes: 0

Bhavin Bhadani
Bhavin Bhadani

Reputation: 22374

try this ...

  if let username = prefs.valueForKey("USERNAME") as? String{
      self.usernameLabel.text = username
  }

or if you want to use NSString .. (Just an option)

 if let username = prefs.valueForKey("USERNAME") as? NSString{
      self.usernameLabel.text = username
  }

Upvotes: 4

Related Questions