-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
  • 307,833
  • 40
  • 508
  • 550
EyeQ Tech
  • 7,024
  • 16
  • 68
  • 123
  • 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,604
  • 23
  • 34
0
 func loadSettings(defaults: UserDefaults) {
    if let driverId = defaults.string(forKey: "driverId"){
     // process driverId
    }
 }
Juri Noga
  • 4,313
  • 7
  • 35
  • 49