Aryan
Aryan

Reputation: 95

Cannot assign value of type '()' to type 'CallbackBlock!'

I am trying to do something in View Controller when an event happens in GameViewController.

So this is what I do

In GameViewController

        typealias CallbackBlock = () -> Void

        public class GameController {
            var onAnagramSolved : CallbackBlock!


    func inSomeMethod(){
       self.onAnagramSolved()
    }
 }

In ViewController

public class ViewController: UIViewController {

    var gameController: GameController!


    public override func loadView() {
        super.loadView()

            gameController = GameController()
    }


    override  public func viewDidLoad() {
        super.viewDidLoad()

        // This is where I get the error (which is the title)
        gameController.onAnagramSolved = self.showLevelMenu()

    }



   func showLevelMenu(){
     // A method showing  UIAlertController

   }

But then I get the Error saying

Cannot assign a value of type '()' to type 'CallbackBlock!'

Its in Swift 3.

Upvotes: 0

Views: 968

Answers (1)

Paulo Mattos
Paulo Mattos

Reputation: 19339

Try removing the () after the method name. That is, changing this line:

gameController.onAnagramSolved = self.showLevelMenu()

to this:

gameController.onAnagramSolved = self.showLevelMenu

The first syntax is for a function call and the other one is for a function reference (i.e., produces a reference to a given function).

A more explicit option would be to use a closure instead:

gameController.onAnagramSolved = { self.showLevelMenu() }

Upvotes: 1

Related Questions