1

Let's say I have this code snipped in the playground

import UIKit

internal final class TestClass {
    internal final var funcPointer: () -> Void

    init() {
        self.funcPointer = self.func1() //Cannot assign value of type '()' to type '() -> Void'
    }

    internal final func func1() {
        print("func1 is called!")
    }
}

var testClass: TestClass = TestClass()
testClass.funcPointer()

Why do I get the shown error message within the init() method and how to initialize a function pointer correctly?

I have already seen this SO post and this tutorial but anyway I don't get it to work for a (Void) -> Void function...

PascalS
  • 975
  • 1
  • 16
  • 40
  • 2
    Did you notice that the answers in the post you linked don't call the function when assigning it to a variable? That was intentional. – molbdnilo May 28 '19 at 15:22
  • 1
    Nit pick: that's not a function pointer, it's a closure. Closures happen to be implemented using function pointers, although even that's not always the case. – Alexander May 28 '19 at 18:58

1 Answers1

3

To assign the closure to the property you have to remove the parentheses

self.funcPointer = self.func1

The subsequent error

self' used in method call 'func1' before all stored properties are initialized

can be fixed by declaring funcPointer implicit unwrapped optional

internal final var funcPointer: (() -> Void)!
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Could you also answer this question? https://stackoverflow.com/questions/56348309/avoid-retain-cycles-for-function-pointers-in-swift-5 :) – PascalS May 28 '19 at 18:46