JLO JLO - 2 years ago 61
iOS Question

Ambiguous error when attempting to filter values using enum

I have a filter that I am trying to use to compare one value to another. Here is the enum that I am using:

enum SomeEnum: String {

case first = "Hey"
case second = "There"
case third = "Peace"

static let values = [first, second, third]

func pickOne() -> String {
switch self {
case .first:
return "value 1"
case .second:
return "value 2"
case .third:
return "value 3"

Here is where I am attempting to filter and find matching values:

array.append(SomeEnum.values.filter({$0.rawValue == anotherArray["id"] as! String}))

I end up getting an ambiguous error:

Cannot convert value of type '[SomeEnum]' to expected argument type 'String'

Any ideas?

Answer Source

The problem is, that SomeEnum.values return type is [SomeEnum] and not String.

And the append function expects the parameter to be String, instead it is [SomeEnum].

This is, what you need to change:

  1. Change append to appendContentsOf, since filter function returns an array, and not a single value
  2. Change the [SomeEnum] to [String] since you are adding it to a [String] array, like this.

This is the fix:

array.appendContentsOf(SomeEnum.values.filter({ $0.rawValue == "SomeString" }).map({ $0.PickOne() }))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download