I can't find the solution to my idea. I get an error. I would like to create a big function that takes an array to change such as [1,2,3,42,342,34,3,3,2,4,5,2,3]
, a list with proper numbers listToFind = [1,2,3,4]
, and an internal function. The internal function creates a dictionary with listToFind
and returns it to a big function where I want to iterate through the array, checking if the i
(value) is in a dictionary.
I'm getting the error:
"Value of type '(Int) -> [Int : Bool]' has no subscripts"
after if someFunc[i] != nil {
func myFuncBig (arrayToChange: [Int], listToTakeToFind: [Int], someFunc: (Int) -> [Int:Bool]) -> [Int] {
var sortedList = [Int]()
for i in arrayToChange {
if someFunc[i] != nil {
sortedList.append(i)
}
}
return sortedList
}
func createDict (array: [Int]) -> [Int:Bool] {
var dictToReturn = [Int: Bool]()
for item in array {
dictToReturn[item] = true
}
return dictToReturn
}
It's not clear how to return a dictionary and find a value by key in it because going through the dictionary like dict[i]
works without closures.
CodePudding user response:
someFunc
is a function that takes an Int
and returns a dictionary, and so it should be
someFunc(i)
.
Try this:
func myFuncBig (arrayToChange: [Int], listToTakeToFind: [Int], someFunc: (Int) -> [Int:Bool]) -> [Int] {
var sortedList = [Int]()
for i in arrayToChange {
if !someFunc(i).isEmpty { // <-- here
sortedList.append(i)
}
}
return sortedList
}
Alternatively, you could use: if someFunc(i)[i] != nil
CodePudding user response:
First of all you have a typo so that the someFunc
parameter should be ([Int]) -> [Int:Bool]
and then you only need to use this function once and return the result to a local variable. Finally you use this variable to check if a number should be included.
func myFuncBig (arrayToChange: [Int], listToTakeToFind: [Int], someFunc: ([Int]) -> [Int:Bool]) -> [Int] {
var sortedList = [Int]()
let dictionary = someFunc(listToTakeToFind)
for i in arrayToChange {
if let flag = dictionary[i], flag {
sortedList.append(i)
}
}
return sortedList
}
Note tough that the dictionary is not really needed, you could let the function return an array instead for all numbers that should be included, thus implying the true
value or skip the collection all together and have a function that directly returns true or false if a given number should be included.
Finally, with the implementation of someFunc
you have in the question this could have been written as
array.filter(listToFind.contains)