Reputation: 277
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
}
Upvotes: 0
Views: 932
Reputation: 236538
UserDefaults has a method called dictionaryForKey exactly for that:
func getMyName() -> String {
return UserDefaults.standard.dictionary(forKey: "account")?["name"] as? String ?? ""
}
Upvotes: 2