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...

2
  • 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. Commented May 28, 2019 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. Commented May 28, 2019 at 18:58

1 Answer 1

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

1 Comment

Could you also answer this question? stackoverflow.com/questions/56348309/… :)

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.