Rachit Rawat Rachit Rawat - 7 months ago 18
Swift Question

Error: Initializer for conditional binding must have optional type, not 'String'

var firstName: String = "John Appleseed"
if let name = firstName {
print ("Hello, \(name)")
}


String Error on second line: Initializer for conditional binding must have optional type, not 'String'

How to decide whether to use optional or non-optional variables?

Answer

First, let's consider what the if let construct means. When you write

if let name = firstName {
    print ("Hello, \(name)")
}

you tell Swift that you want to

  1. Try unwrapping firstName
  2. If the result of unwrapping is successful, assign the result of unwrapping to name
  3. If the result of unwrapping is successful, print "Hello, \(name)"

In other words, this construct is for dealing with unwrapping of optional variables. However, variable firstName is not optional; there is nothing to unwrap, causing Swift to complain.

Comments