gpt4 book ai didi

swift - 使用 swift 字典返回它的所有值?

转载 作者:可可西里 更新时间:2023-11-01 00:00:26 25 4
gpt4 key购买 nike

我有一个 swift 字典 myD,它以 myEnum 类型的枚举作为键,以 () 函数作为值。当我尝试其中一个键的功能时,所有功能都会被调用。请帮忙。下面是代码:

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

当我运行应用程序时,无论我将 .one 还是 .two 放入 runFuncForCase(_:) 函数中,consle 总是打印“1”和“2”,这意味着两个函数都运行了。

最佳答案

通过这个字典声明,字典的值类型是Void,它只能包含空元组()

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

并且 foo1()foo2()myD 的 getter 被调用时被评估。不是在 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 的强引用。

在实际应用中,你应该:

  • 使 foo1foo2 成为顶级函数

  • 这样写:

    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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com