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
try using
var PlayerEquipped: AnyObject
or its Optional equivalent
var PlayerEquipped: AnyObject?
You have a couple of options depending on what you want to achieve:
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With