O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Optional binding with the guard statement

We can use the guard statement with optional binding to verify that an optional has a valid value. The following example illustrates this:

func sayHello(name: String?) { 
  guard let internalName = name else { 
    print("Name has not value") 
    return 
  } 
  print("Hello \(internalName)") 
} 

In the sayHello(name:) function, we use the guard statement to verify that the name parameter contains a valid value, and if not, we print out the message Name has no value. If the name parameter does have a valid value, we then print out a hello message. The one thing to note from this example is that the internalName constant is scoped for the function; therefore, we can use it throughout the function. This is different from ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required