2

I understand that The text property of UILabel is optional, I tried adding an else but i'm not sure what else to add.

productData.product.productName is me getting the name of the product from the database

            if var pName = productData.product.productName { //error
              self.productName.text = pName
            }

@IBOutlet weak var pName: UILabel!

Initializer for conditional binding must have Optional type, not 'String' is the error I get, It was working I think im not sure where its gone wrong

kmnflask
  • 175
  • 1
  • 12

2 Answers2

0

It states that the use of if condition is unnecessary, because the 'productName' is not optional.

You can directly add the value to your label.

self.productName.text = productData.product.productName //Product name is not optional

Optional chaining is used when you try to get a optional value. For example, if you want to get the text of label then you'll require if condition.

if var text = self.productName.text { //Text in label is optional
   print(text)
}
sinner
  • 483
  • 3
  • 14
0

It seems like the compiler is complaining that productData.product.productName is NOT an Optional. The if var name = ____ construct only works on Optionals.

If you are testing for a non-empty String, you may want to check the count or isEmpty instead.

Mike Hay
  • 2,828
  • 21
  • 26