Home > other >  Cannot convert value of type 'Object.Type' to expected argument type 'Object'
Cannot convert value of type 'Object.Type' to expected argument type 'Object'

Time:09-17

I am a newbie to Swift so I apologize if this is dumb question. I am trying to allocate an object and pass it the parent's self.

What I have is like:

  class Maze { 
      var rat : MazeRat 

      init () {
        
        rat = MazeRat(self: Maze)
    }

  }

and

class MazeRat{
     init( maze : Maze ) {
        
    }
}

But XCode objects to "self" in the call, insisting it should be 'maze'. But if that change is made I get the error:

  Cannot convert value of type 'Maze.Type' to expected argument type 'Maze'

TIA for any help.

CodePudding user response:

You should refer to the current instance of Maze as self.

Notice in each example the use of the unowned or weak keywords here, to prevent a strong reference between Maze and MazeRat.

However, since self isn't available yet as rat hasn't been initialized - you need to give rat an initial value first.

Example:

class Maze {
    private(set) var rat: MazeRat!

    init() {
        rat = nil
        rat = MazeRat(maze: self)
    }
}

class MazeRat {
    unowned let maze: Maze

    init(maze: Maze) {
        self.maze = maze
    }
}

Another method is to initialize MazeRat, then set the maze instance, like so:

class Maze {
    let rat: MazeRat

    init() {
        rat = MazeRat()
        rat.maze = self
    }
}

class MazeRat {
    weak var maze: Maze?

    init() {}
}
  • Related