[英]Passing functions as arguments error: Cannot convert value of type “someType.type” to expected argument type “someType”
I have a function, which takes several other functions as arguments: 我有一个函数,它将其他几个函数用作参数:
class Iterator {
func iterateItems(itemArray: [Items], removeItem: (Items) -> Void, addItem: (inout Items) -> Void, calculateEfficiency: () -> Void) -> [Items] {
// function body
}
}
And I call it in its class' subclass like this: 我在其类的子类中这样称呼它:
class WPCalculator: Iterator {
func removeWeaponItem(item: WeaponItems) { ... }
func addWeaponItem(item: inout WeaponItems) { ... }
func calcWeaponDamage() { ... }
func iterateWPItems() {
iterateItems(itemArray: WeaponItems.weaponItems, removeItem: removeWeaponItem(item: WeaponItems), addItem: addWeaponItem(item: &WeaponItems), calculateEfficiency: calcWeaponDemage())
}
}
Then Xcode says error on removeItem
and addItem
parameter: 然后Xcode对removeItem
和addItem
参数说错误:
Cannot convert value of type "WeaponItems.type" to expected argument type "WeaponItems" 无法将类型“ WeaponItems.type”的值转换为预期的参数类型“ WeaponItems”
Also the WeaponItems
class is a subclass of Items
class: 而且WeaponItems
类也是Items
类的子类:
class WeaponItems: Items { ... }
Why is that error message? 为什么显示该错误信息?
You are passing a class WeaponItems
instead of class objects. 您正在传递类WeaponItems
而不是类对象。 Following is more correct version: 以下是更正确的版本:
func iterateWPItems() {
let itemsToRemove = WeaponItems() //initialize object somehow
var itemsToAdd = WeaponItems() //initialize object somehow
iterateItems(itemArray: WeaponItems.weaponItems, removeItem: removeWeaponItem(item: itemsToRemove), addItem: addWeaponItem(item: &itemsToAdd), calculateEfficiency: calcWeaponDemage())
}
EDIT : Sorry, I've got your problem. 编辑 :对不起,我有你的问题。 Than instead of calling these methods you should just pass them as arguments , so you don't have to put parentheses to a trail of method name: 比起调用这些方法,您应该仅将它们作为参数传递 ,这样就不必在方法名称的后面加上括号:
func iterateWPItems() {
iterateItems(itemArray: WeaponItems.weaponItems, removeItem: removeWeaponItem, addItem: addWeaponItem, calculateEfficiency: calcWeaponDemage)
}
Within your invocation of iterateItems, removeWeaponItem(item: WeaponItems)
, WeaponItems
is a type, since it is the same as the class name WeaponItems
. 在对iterateItems的调用中, removeWeaponItem(item: WeaponItems)
, WeaponItems
是一种类型,因为它与类名WeaponItems
相同。 If you create variables of type WeaponItems, and name them differently (eg, weaponItems) instead of WeaponItems, you probably will not run into this problem. 如果您创建WeaponItems类型的变量,并用不同的名称(例如,武器物品)而不是武器物品命名,则您可能不会遇到此问题。
I found the problem: the way I passed functions as arguments is wrong, it should be like this: 我发现了问题:我将函数作为参数传递的方式是错误的,应该是这样的:
func iterateWPItems() {
iterateItems(itemArray: WeaponItems.weaponItems, removeItem: removeWeaponItem as! (Items) -> Void, addItem: addWeaponItem as! (inout Items) -> Void, calculateEfficiency: calcWeaponDemage())
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.