Reputation: 865
I'm trying to filter from a dictionary.
My code is below:
var newSimHistoryArr = [] as NSArray
if self.filterBy == kPending {
newSimHistoryArr = (dic["simHistory"] as! [AnyObject]).filter {
return $0 is NSDictionary
}
} else {
for a in dic["simHistory"] as! [AnyObject] {
if a is SimHistory {
newSimHistoryArr = (dic["simHistory"] as! [AnyObject]).filter {
return ($0 as! SimHistory).status == self.filterBy
}
break
}
}
}
It worked fine before I converted my project to Swift 3.
The error is on these lines:
newSimHistoryArr = (dic["simHistory"] as! [AnyObject]).filter{ return ($0 is NSDictionary)}
newSimHistoryArr = (dic["simHistory"] as! [AnyObject]).filter{ return ($0 as! SimHistory).status == self.filterBy}
The error is:
Cannot invoke 'filter' with an argument list of type '((AnyObject) throws -> Bool)'
I have no idea what went wrong ...
Upvotes: 0
Views: 2389
Reputation: 1232
I had a similar problem to this. In my case just wrapping the whole right side expression into parenthesis did the trick in case anybody wonders.
Upvotes: 0
Reputation: 3323
Digesting the problem down to it's minimal level, the following code, which you can run in playground, illustrates the error:
var newSimHistoryArr = [] as NSArray
var oldHistory = ["book", "bath", "table"]
newSimHistoryArr = oldHistory.filter { $0.hasPrefix("b") }
Error message is:
Playground execution failed: error: MyPlayground.playground:2:32: error: cannot invoke 'filter' with an argument list of type '((String) throws -> Bool)' newSimHistoryArr = oldHistory.filter { $0.hasPrefix("b") }
Curiously the error occurs, not because of the filter expression itself, but because of the data type it is being cast to i.e. the data type of the LEFT HAND SIDE of the assignment. This is very misleading from the compiler.
Change the data type for newSimHistoryArr to a compatible type and it all works.
var newSimHistoryArr:[String]
var oldHistory = ["book", "bath", "table"]
newSimHistoryArr = oldHistory.filter { $0.hasPrefix("b") }
or even the more cumbersome form:
var newSimHistoryArr = [] as NSArray
var oldHistory = ["book", "bath", "table"]
newSimHistoryArr = (oldHistory.filter { $0.hasPrefix("b") }) as NSArray
Upvotes: 2
Reputation: 815
You should be able to drop the return
at the beginning of the anonymous functions you are passing to filter
.
The function being passed to filter probably shouldn't throw
. Your expressions do, so maybe you need to insert a try in there and return false
when they throw.
I'm not seeing why the is
operator might throw, but the as!
looks scary. Perhaps using the as?
operator combined with a guard
might do the trick to avoid the potential of things going awry by converting a potential casting error into an optional result which is easier to handle.
Upvotes: -2