简体   繁体   中英

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?

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)
} 

Within your invocation of iterateItems, removeWeaponItem(item: WeaponItems) , WeaponItems is a type, since it is the same as the class name 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.

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())
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM