Search code examples
iosswiftuibuttoniboutletcollection

Getting An Item from IBOutletCollection in Swift


I'm getting an error as "Type of expression is ambiguous without more context"

Here is my code

@IBOutlet var customerDashboardButtons:[NSArray]?

var predicate = NSPredicate(format: "SELF.tag == %d", tag)
var filteredButtons = customerDashboardButtons!.filter { predicate.evaluateWithObject($0) };
if 0 < filteredButtons.count {
      var button = customerDashboardButtons!.first
      button.hidden = true // getting an error in this line as "Type of expression is ambiguous without more context
 }

I have tried the following,

var button:UIButton = customerDashboardButtons!.first //Error "NSArray? is not convertible to UIButton"

var button = customerDashboardButtons!.first as UIButton //Error "NSArray? is not convertible to UIButton"

Any help on this is appreciated.


Solution

  • @IBOutlet var customerDashboardButtons:[NSArray]?
    

    Creates an array of arrays.
    Calling customerDashboardButtons!.first will return the first array (the NSArray) in your array (the […] will also create an array)

    I suspect you want your customerDashboardButtons to be an array of UIButton’s so you would use

    @IBOutlet var customerDashboardButtons:[UIButton]?
    

    Using customerDashboardButtons!.first here will give you a UIButton. Since the type of the array is UIButton, you don’t have to declare your button as UIButton.

      var button = customerDashboardButtons!.first
    

    Will work if you change your array.