Bright Future Bright Future - 2 months ago 16
Swift Question

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:


Cannot convert value of type "WeaponItems.type" to expected argument type "WeaponItems"


Also the
WeaponItems
class is a subclass of
Items
class:

class WeaponItems: Items { ... }


Why is that error message?

Answer

You are passing a class WeaponItems instead of class objects. 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)
}