在Swift中是否有相当于Ruby的instance_eval?

时间:2017-06-25 15:19:38

标签: swift

在ruby中,我可以将一个块传递给一个方法,并在接收对象的上下文中对块进行求值。

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中完成,它具有带接收器的功能类型的想法。

例如,以下产生类似于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

1 个答案:

答案 0 :(得分:1)

我不知道在语言中这样做的方法。您可以通过actionReceiver实例作为输入手动执行此操作,然后在action(self)内调用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