1

I want to check if there is a value on a certain variable. If there isn't I want to return a default value. How is the best pratice of doing this?

I would like to do something like:

let defaults = Userdefaults()
if let name = defaults.string(foKey "name") { 
    return name 
} else {
    return "john"
}
Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
ErikLm
  • 401
  • 1
  • 6
  • 12
  • 3
    There's also `UserDefaults.standard.register(defaults:)`. Possible duplicate of https://stackoverflow.com/q/37830558/2227743. – Eric Aya Dec 11 '17 at 11:57

2 Answers2

4

You should be able to do this..

let defaults = UserDefaults.standard
let name = defaults.string(foKey "name") ?? "john"

?? in Swift is called The nil-coalescing operator

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Scriptable
  • 19,402
  • 5
  • 56
  • 72
3
return UserDefaults.standard.string(forKey: "name") ?? "john"
Adnan Aftab
  • 14,377
  • 4
  • 45
  • 54