gpt4 book ai didi

arrays - 如何制作一个函数,将协议(protocol)中定义的任何函数作为其参数?

转载 作者:行者123 更新时间:2023-11-28 06:53:30 24 4
gpt4 key购买 nike

我正在开发一款纸牌游戏,我想制作一个循环遍历我的 Players 数组的函数并为每个玩家执行一些功能,所以我没有成吨的东西

for var player in Players {
player.doSomeFunction()
}

遍及我的代码。相反,我想要类似下面的内容:

func everyone(doThis: func) {
for var player in Players {
player.doThis(<params, etc…>)
}
}

这样我就可以调用Players.everyone(doThis(params, etc…))在代码的其他地方,而不是每次我需要让所有玩家做某事时都循环遍历玩家。

我如何制作一个函数,将协议(protocol)中定义的任何函数作为其参数?我遇到的问题是,当您在 Swift 中使用函数作为参数时,您似乎必须在函数声明中定义函数参数的参数和返回类型。或者,是否有内置方式调用 Players.forAllElements(doThisFunction) (其中 Players 是一个 Array<Player> )?

如果有帮助,我有两个符合 Player 的类协议(protocol):ComputerPlayerHumanPlayer .

最佳答案

似乎没有办法在 swift 中表达 any-function-in-a-protocol,以用于某种参数类型的定义。

但是,对于 currying和函数类型你可以做一些类似的事情:您可以针对具有相同签名的所有函数:

class Player {
var name: String
init(_ name: String) {
self.name = name
}

// Both actions, even if they have different parameter names,
// have the same function signature
func actionOne(foo: String, count:Int) {
print("actionOne:\(name):\(foo):\(count)")
}

func actionTwo(bar: String, amount: Int) {
print("actionTwo:\(name):\(bar):\(amount)")
}
}

let players = [Player("Primero"), Player("Segundo")]

// A function type that receives a Player object, and returns a
// function with the `String, Int` signature
typealias PlayerActionType = (Player) -> (String, Int) -> ()

// This is the function that takes the curried function, and can
// run any function sharing the same signature
func performAction(curriedFunction: PlayerActionType) {
for currentPlayer in players {
let actionFunction = curriedFunction(currentPlayer)
actionFunction("string", 3)
}
}

performAction(Player.actionOne)
performAction(Player.actionTwo)

// Prints:
// actionOne:Primero:string:3
// actionOne:Segundo:string:3
// actionTwo:Primero:string:3
// actionTwo:Segundo:string:3

关于arrays - 如何制作一个函数,将协议(protocol)中定义的任何函数作为其参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34304896/

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