How do I declare, create, and use method pointers in Swift?

泪湿孤枕 提交于 2019-12-01 21:21:20

问题


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
    }

    //...
}

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.


回答1:


See if this helps you.

class Something {
    var f: ( () -> Int )?
    let f1 = { () -> Int in /* do some action here */ return 1}
    let f2 = { () -> Int in /* do some action here */ return 2}

    func ff(which: Bool) {
        f = which ? f1 : f2
    }

    func act() {
        if let f = f {
            f()
        }
    }
}



回答2:


Here is how I do it -

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() output:

I Was passed 4
I was returned


来源:https://stackoverflow.com/questions/36025632/how-do-i-declare-create-and-use-method-pointers-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!