Search code examples
iosswiftblocktype-alias

block in Swift : return error " is not convertible to "


I made a mistake but I cannot see how to solve it. I would like to load all the assets from GameScene and send a Bool in a completion method. I use typealias : should it be renamed twice for the two files (gameScene and gameController)?

Then I have got an error on this line GameScene.loadSceneAssetsWithCompletionHandler{ :

((Bool) -> Void) is not convertible to 'GameScene'

Here is the code :

    //gameController:
    typealias OnComplete = (Bool) -> ()
    override func viewDidLoad() {
        super.viewDidLoad()

        GameScene.loadSceneAssetsWithCompletionHandler{ (success:Bool)->Void in
            println("2/ yes")
            return
        }



    //gameScene : rewrite typealias? 
    typealias OnComplete = (Bool) -> ()

    func loadSceneAssetsWithCompletionHandler( completion:OnComplete ) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in
            self.loadSceneAssets()

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                println("1/ yes")
                completion(true)
            })//main
        })//global
    }

I read some threads that said to add a "return", but it does not solve the error here.

Thanks


Solution

  • It's almost working, but you've got a couple things going wrong here. First of all, you can't redeclare a typealias. Second of all you're calling loadSceneAssetsWithCompletionHandler as a class function when it's set up as an instance function. Note changes:

    typealias OnComplete = (Bool) -> ()
    class GameController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            GameScene.loadSceneAssetsWithCompletionHandler { success in
                println("2/ yes")
                return
            }
        }
    
    }
    
    
    class GameScene:  UIViewController {
    
        func loadSceneAssets() {
    
        }
    
        class func loadSceneAssetsWithCompletionHandler( completion:OnComplete ) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
               let gameScene = GameScene()
               gameScene.loadSceneAssets()
    
                dispatch_async(dispatch_get_main_queue()) {
                    println("1/ yes")
                    completion(true)
                }
            }
        }
    }