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.

CTMacUser
  • 1,996
  • 1
  • 16
  • 27
  • 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. https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html – ryantxr Mar 16 '16 at 04:41
  • From looking at [this Tweet](https://twitter.com/JadenGeller/status/619426292232908800), I don't think `mutating` methods are supported, even if I can figure out how to call non-`static` methods. – CTMacUser Mar 16 '16 at 09:01
  • My attempts frequently end at "Partial application of 'mutating' method is not allowed". – CTMacUser Mar 16 '16 at 09:09

2 Answers2

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()
        }
    }
}
ryantxr
  • 4,119
  • 1
  • 11
  • 25
  • I tried it. It works, but I could *not* access `self` or any properties from `f1` or `f2`, so it's useless to me. – CTMacUser Mar 16 '16 at 09:00
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
J-Dizzle
  • 4,861
  • 4
  • 40
  • 50