我有Swift Dictionary,它的Enums类型为“关键字”,函数为“值”。
当我尝试其中一个键的函数时,所有函数都会被调用。请帮忙。下面是代码:

class myScene: SKScene {
    enum myEnum {
        case one
        case two
    }

    func foo1() { print(1) }
    func foo2() { print(2) }

    var myD: [myEnum : ()] {
        return [
            .one : foo1(),
            .two : foo2()
        ]
    }

    func runFuncForCase(_ ca: myEnum) {
            myD[ca]
    }

    override func didMove(to view: SKView) {
        runFuncForCase(.one) //HERE!!!!!
    }

}
当我运行应用程序时,不管我把myDmyEnum放在()函数中,consle总是打印“1”和“2”,这意味着两个函数都运行了。

最佳答案

使用字典的这个声明,字典的值类型是Void,它只能包含空tuple()

var myD: [myEnum : ()] {
    return [
        .one : foo1(),
        .two : foo2()
    ]
}

当调用foo1()的getter时,会对foo2()myD进行评估。下标myD后不显示。(它们的返回类型为Void,因此它们被视为返回空元组。)
您可能需要这样写:
class myScene: SKScene {
    enum myEnum {
        case one
        case two
    }

    func foo1() { print(1) }
    func foo2() { print(2) }

    var myD: [myEnum : ()->Void] { //### value type of the dictionary needs to be a function type
        return [
            .one : foo1,    //### actual value of the dictionary needs to be a function itself,
            .two : foo2,    // not the result of calling the function
        ]
    }

    func runFuncForCase(_ ca: myEnum) {
        myD[ca]!()   //### To invoke the function, you need `()`
    }

    override func didMove(to view: SKView) {
        runFuncForCase(.one)
    }
}

需要注意的一些注意事项
上面的代码稍微简化了一点,它忽略了创建保留循环的风险,因为实例方法隐式地持有self的强引用。
在实际应用程序中,您应该:
使顶层功能

这样写:
var myD: [myEnum : ()->Void] {
    return [
        .one : {[weak self] in self?.foo1()},
        .two : {[weak self] in self?.foo2()},
    ]
}

关于swift - 使用swift字典会返回其所有值吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45118955/

10-11 23:05
查看更多