-4

I find checking nil before unwrapping is lengthy, is there a shorter way? I'm new to Swift, thanks

     func loadSettings(defaults: UserDefaults) {
       if defaults.string(forKey: "driverId") != nil {
         driverId = defaults.string(forKey: "driverId")!

       }
     } 
rmaddy
  • 314,917
  • 42
  • 532
  • 579
EyeQ Tech
  • 7,198
  • 18
  • 72
  • 126
  • 6
    This is all clearly explained with lots of examples in the Optionals section of [The Swift Programming Language](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/) book. – rmaddy Nov 03 '16 at 15:16

2 Answers2

0

Sure:

if let driverId = defaults.string(forKey: "driverId") {
    // use driverId
}
Bogdan Farca
  • 3,856
  • 26
  • 38
0
 func loadSettings(defaults: UserDefaults) {
    if let driverId = defaults.string(forKey: "driverId"){
     // process driverId
    }
 }
Juri Noga
  • 4,363
  • 7
  • 38
  • 51