Rachit Rawat Rachit Rawat - 2 years ago 168
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download