-1

I'm interested why I'm getting this error:

Initializer for conditional binding must have Optional type, not [String]

Here is my code:

class MainVC: UIViewController {
    @IBOutlet weak var typesField: IQDropDownTextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        let elements: Array<String?> = ["Electronics", "Cars", "Toys"]
        typesField.isOptionalDropDown = false
        typesField.itemList = (elements as? [String])!    
    }

    @IBAction func savePressed(_ sender: UIButton) {
        var item: Item!

        if let types = typesField.itemListUI {
            item.type = types
        }
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Latenec
  • 408
  • 6
  • 21
  • Which line exactly is actually causing the error? – rmaddy Jul 15 '17 at 16:26
  • if let types = typesField.itemListUI { -> this one – Latenec Jul 15 '17 at 16:27
  • whenever you use `if let` the right side *must* be an **optional** (which may or may not have a value). For more see [here](https://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language/38830543#38830543). **Non-optionals** may not ever be `nil` so *for sure* it has a value; in your case the value *is* a `string` and isn't `string?`. You can just write that line as `types = typesField.itemListUI` —without the `if let`. – mfaani Jul 15 '17 at 16:29
  • you mean `let types = typesField.itemListUI` - because at first I have to create variable `types ` – Latenec Jul 15 '17 at 16:35
  • You could have just skipped that line and just done : `item.type = typesField.itemListUI` – mfaani Jul 15 '17 at 16:36

1 Answers1

0

Initializer for conditional binding must have Optional type, not [String]

means the right side of the expression (typesField.itemListUI) is not optional and the optional binding is not needed

So instead

if let types = typesField.itemListUI {
   item.type = types
}

just write

item.type = typesField.itemListUI

No if let, no extra local variable.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • I'm getting this error — Cannot assign value of type '[String]' to type 'String?' – Latenec Jul 15 '17 at 16:40
  • Apparently `item.type` is declared as (single) `String` not as array of `String` (`[String]`). You have to resolve this in your design. – vadian Jul 15 '17 at 16:41