如何使用字典调用函数?

时间:2018-09-18 16:03:52

标签: arrays swift function dictionary

我尝试创建一个Dictionary来调用某些函数。

我的数组使用一个键Int,一个String和一个函数,如下所示:

let list_weapons: [Int: [Any]]  = [1: ["Sword", attack_sword],
                                   2: ["Magic wand", heal_magic_wand],
                                   3: ["Hammer", attack_hammer],
                                   4: ["Axe", attack_axe]]

这些函数将Class作为参数,如下所示:

func attack_sword(character: Character)

我试图那样调用我的函数,但是它不起作用。

list_weapons[1]![1](character: Character) 
  

无法调用非功能类型“任何”的值

如果您有任何想法或建议我使用其他容器

谢谢

4 个答案:

答案 0 :(得分:2)

您无需将方法存储在字典中即可解决问题。我认为,这里的架构解决方案会更好。如果愿意,您可以与选择器一起玩,但是我想,只要您做这样的事情,事情就会容易得多

// Here you can specify all common thing about your weapons
protocol Weapon: class {
    var name: String { get }
    func attack(character: Character)
}

// Each weapon has its own class which can contain eveything you need
class Sword: Weapon { }
class MagicWand: Weapon { }
class Hammer: Weapon { }
class Axe: Weapon { }

// That's how you can store you weapons list
// You can use a dictionary if you like
let weaponsArray: [Weapon]  = [Sword(),
                               MagicWand(),
                               Hammer(),
                               Axe()]

// And that's how you can use them
weaponsArray[0].attack(character: character)

答案 1 :(得分:0)

使用前,您必须cast 任何使用功能

let f = (list_weapons[1]![1] as! (Character) -> Void)
f("a") //it will invoke attack_sword("a")

并且没有temp变量,

(list_weapons[1]![1] as! (Character) -> Void)("a")

答案 2 :(得分:0)

使用WITH src AS ( SELECT ROWNUM, line, text, origin_con_id FROM sys.all_source WHERE type = :type AND owner = :owner AND name = :name ) SELECT text FROM src, ( SELECT MAX(origin_con_id) max_orig FROM src ) WHERE origin_con_id = max_orig ORDER BY line 数组存储字符串和带有特定签名的闭包(函数)是一个糟糕的选择。最好声明一个具有正确类型的两个属性的Any。然后将这些结构存储在字典中。

struct

答案 3 :(得分:0)

您可以将元素转换为函数类型:

if let attack = list_weapons[1]![1] as? ((Character) -> Void) {
    attack(...)
} else {
    print("Cannot attack")
}

但是您最好重新设计数据模型。使用字典会很快造成混乱。这是一种实现方法:

protocol Weapon {
    var name: String { get }
    func attack(character: Character)
}

struct Sword: Weapon {
    let name = "Sword"
    func attack(character: Character) { ... }
}

struct MagicWand: Weapon {
    let name = "Magic Wand"
    func attack(character: Character) { ... }
}

struct Hammer: Weapon {
    let name = "Hammer"
    func attack(character: Character) { ... }
}

struct Axe: Weapon {
    let name = "Axe"
    func attack(character: Character) { ... }
}

let weapons: [Weapon] = [Sword(), MagicWand(), Hammer(), Axe()]
weapons[1].attack(character: ...)

您以不同的伤害,独特的功能,等级等扩展每种武器。