gpt4 book ai didi

swift - 在 Swift 中是否有与 Ruby 的 instance_eval 等效的东西?

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

在 ruby​​ 中,我可以将一个 block 传递给一个方法,并在接收对象的上下文中评估该 block 。

class Receiver

def method_a
puts "hello from method_a"
end

def method_b
puts "hello from method_b"
end

def define_something &action
method_a
instance_eval &action
end

end

thing = Receiver.new
thing.define_something { method_b }

产生以下输出:

hello from method_a
hello from method_b

在 Swift 中实现这样的东西的正确方法是什么?

这就是我所拥有的,但是 Xcode 当然会提示 methodB 是一个未解析的标识符。

class Receiver {

func methodA() {
print("hello from method A")
}

func methodB() {
print("hello from method B")
}

func defineSomething( action: () -> Void ) {
methodA()
action()
}
}

let thing = Receiver()
thing.defineSomething { methodB() }

顺便说一句,这也可以在 Kotlin 中完成,Kotlin 具有带接收器的函数类型的想法。

例如,以下生成的输出与 ruby​​ 示例生成的输出类似。

class Receiver {
fun methodA() = println("hello from methodA")
fun methodB() = println("hello from methodB")
fun defineSomething( action: Receiver.() -> Unit) {
methodA()
action()
}
}

fun main(args: Array<String>) {
val thing = Receiver()
thing.defineSomething { methodB() }
}

hello from methodA
hello from methodB

最佳答案

我不知道有什么方法可以用该语言做到这一点。您可以通过让 actionReceiver 实例作为输入,然后在 defineSomething( Action :)

class Receiver {

func methodA() {
print("hello from method A")
}

func methodB() {
print("hello from method B")
}

func defineSomething(action: (_: Receiver) -> Void ) {
methodA()
action(self)
}
}

let thing = Receiver()
thing.defineSomething { $0.methodB() }
 hello from method A
hello from method B

关于swift - 在 Swift 中是否有与 Ruby 的 instance_eval 等效的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44747749/

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