Reputation:
extension Array{
func addBonus(addFunc:([Int])->([Int])) ->[Int]{
return addFunc(self)//error in this line
}
}
var empSalArray:[Int] = [2500,1300,1244,3412,5432,1223]
var empBonusAddedArry = empSalArray.addBonus{ arr -> [Int] in
var temp = [Int]()
for val in arr{
temp.append(val+1000)
}
return temp
}
print(empBonusAddedArry)
Wanted to create an extension of Array..so that i can call as sort
array.sort(){}
However returns error as
Cannot convert value of type Array to expected argument type [Int].
Upvotes: 0
Views: 116
Reputation: 539685
addFunc(self)
in your extension method does not compile because the array need not be an array of Int
elements.
In this case, it is easy to fix:
extension Array {
func addBonus(addFunc:([Element])->([Element])) ->[Element]{
return addFunc(self)
}
}
where Element
is the generic placeholder type for the array.
Alternatively, you could consider to define the extension method as
extension Array{
func addBonus(addFunc:(Element)-> Element) ->[Element]{
return self.map(addFunc)
}
}
where a transform function for an array element instead of the entire array is passed:
var empSalArray:[Int] = [2500,1300,1244,3412,5432,1223]
var empBonusAddedArry = empSalArray.addBonus { amount in amount + 1000 }
print(empBonusAddedArry)
Of course you would get the same result with the built-in
map()
method:
var empSalArray:[Int] = [2500,1300,1244,3412,5432,1223]
var empBonusAddedArry = empSalArray.map { amount in amount + 1000 }
print(empBonusAddedArry)
Upvotes: 2