如何在Swift中声明,创建和使用方法指针? [英] How do I declare, create, and use method pointers in Swift?

查看:82
本文介绍了如何在Swift中声明,创建和使用方法指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是在谈论C函数的指针,而是在Swift类型中的方法。

I'm not talking about pointers to C functions, but to a method within a Swift type.

struct Test: GeneratorType {
    var methodPointer: mutating () -> Bool?  // Non-working guess
    var which: Bool

    init() {
        which = false
        methodPointer = which ? &testMethod1 : &testMethod2  // Also non-working guess
    }

    //...
}

编译器说 变异作为函数声明的一部分是不合法的。 (实际上,它只是建议在其中使用分号。)对于指针初始化(在删除 muting 之后),编译器认为我正在尝试调用函数,并改用他们的结果。我想在这里将这些方法用作对象本身,而不是用作函数调用。稍后,我想在 next 中使用指向方法;在不弄清楚这一点的情况下,我将不得不求助于枚举标志并手动选择在 next 中调用哪种方法。

The compiler says "mutating" isn't legal as part of a function declaration. (Actually, it just suggests a semi-colon there.) And for the pointer initialization (after I remove mutating), the compiler thinks I'm trying to call the functions and use their results instead. I want to use the methods as objects in-and-of themselves here, not as a function call. Later on I want to use the pointed-to method within next; without figuring this out, I'll have to resort to an enumeration flag and manually choosing which method to call within next.

我希望封闭机制的某些部分允许这样做。也许像此页面描述了返回函数的函数。但是我见过的示例都没有提到变异方法。

I hope there's some part of closure mechanics that allows this. Maybe something like this page, which describes functions returning functions. But none of the examples I've seen mention mutating methods.

推荐答案

这是我的工作方式-

class FcnArgs {                             //@goal  pass a fcn as arg

    class func demo() {
        let fPtr = funcToPointTo;           //@type  '((Int)->String)'
        print(fPtr(4));
    }

    class func funcToPointTo(_ i : Int) -> String {
        print("I Was passed \(i)"); 
        return "I was returned";
    }
}

FcnArgs.demo()输出:

FcnArgs.demo() output:

I Was passed 4
I was returned

这篇关于如何在Swift中声明,创建和使用方法指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆