4

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.

3
  • The link you provided was from July 2014 and should not be trusted. That was a month after Swift came out and those articles tend to be misleading, incorrect and obsolete. You can try Swift docs on closures. developer.apple.com/library/prerelease/ios/documentation/Swift/… Commented Mar 16, 2016 at 4:41
  • From looking at this Tweet, I don't think mutating methods are supported, even if I can figure out how to call non-static methods. Commented Mar 16, 2016 at 9:01
  • My attempts frequently end at "Partial application of 'mutating' method is not allowed". Commented Mar 16, 2016 at 9:09

2 Answers 2

0

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()
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I tried it. It works, but I could not access self or any properties from f1 or f2, so it's useless to me.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.