John Doe John Doe - 2 months ago 15
Swift Question

Get string from object in Swift 3

In Swift 2.3 I had the following code:

func getMyName() -> String {
return NSUserDefaults.standardUserDefaults().objectForKey("account")!["name"] as! String
}


Now, I am trying to convert this code to Swift 3, but I am struggling with this error:


Type 'Any' has no subscript members


Here's my migrated code:

func getMyName() -> String {
return UserDefaults.standard.object(forKey: "account")!["name"] as! String
}

Answer

UserDefaults has a method called dictionaryForKey exactly for that:

func getMyName() -> String {
   return UserDefaults.standard.dictionary(forKey: "account")?["name"] as? String ?? ""
}