Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a empty variable that can take the value type of a class

Tags:

xcode

ios

swift

Hey I'm trying to figure out how to either set a variable to the type of an empty class. Like this if it weren't an error:

Code:

  var PlayerEquipped = class() // failed attempt at trying set up a blank variable that can take the type of a class

Or make a variable that i can change in the future. So basically i can create a global variable like this with a class assigned to it with no problems.

Code:

   var PlayerEquipped = House()

          //In another .swift file i have the 2 classes

    class House {
    init() {
     }
    }

    class House2 {
    init() {
     }
    }

But even though its setup with "var" i still get an error when i try to change that "SelectClass" variable to a different class. For example If i were to make a string variable with text "Hello" in-side then later down in my view did load decide to change that variable text to "GoddBye" it would let me do that. But if i try to change the "SelectedClass" Variable to a different class I get this error. It saying 'cannot assign value of type saintsRB to type saintsLB' Code:

      var PlayerEquipped = House()

   //down in view didload:
       PlayerEquipped = House2() // Error here

Picture of Error

like image 838
Hunter Avatar asked Sep 04 '16 11:09

Hunter


2 Answers

try using

var PlayerEquipped: AnyObject

or its Optional equivalent

var PlayerEquipped: AnyObject?
like image 123
meowmeowmeow Avatar answered Oct 30 '22 06:10

meowmeowmeow


You have a couple of options depending on what you want to achieve:

  1. Make a protocol (e.g. Buildable). Have all your houses implement it. Declare your variable as Buildable (e.g. var house:Buildable? - note the ?, so you don't have to init it, it could be nil) - This is usually how I would do it, trying to avoid inheritance

  2. Make a class (e.g House). Have all your houses (House1, House2, etc) inherit form House. Declare your variable as House (e.g. var house:House?)

Declaring as Any or AnyObject might be valid, but it limits you heavily and it's probably not what you want to do in this situation.

And as an advice, try to grasp these basic principles before going forward and code.

like image 28
Rad'Val Avatar answered Oct 30 '22 07:10

Rad'Val