简体   繁体   中英

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?

抛出错误

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
  }

change NSString to String,

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

its working fine, hope its helpful

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