Hunter Hunter - 3 months ago 8
iOS Question

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

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

Answer

try using

var PlayerEquipped: AnyObject

or the its Optional equivalent

var PlayerEquipped: AnyObject?