xcode 如何创建一个可以采用类的值类型的空变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39316290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a empty variable that can take the value type of a class
提问by Hunter
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”进行设置,当我尝试将“SelectClass”变量更改为不同的类时,我仍然会收到错误消息。例如,如果我要在内部创建一个带有文本“Hello”的字符串变量,那么稍后在我看来确实负载决定将该变量文本更改为“GoddBye”,它会让我这样做。但是,如果我尝试将“SelectedClass”变量更改为不同的类,则会出现此错误。它说'不能将类型 SaintsRB 的值赋给类型 SaintsLB' 代码:
var PlayerEquipped = House()
//down in view didload:
PlayerEquipped = House2() // Error here
回答by meowmeowmeow
try using
尝试使用
var PlayerEquipped: AnyObject
or its Optional equivalent
或它的 Optional 等价物
var PlayerEquipped: AnyObject?
回答by Valentin Radu
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 inheritanceMake a class (e.g
House
). Have all your houses (House1
,House2
, etc) inherit formHouse
. Declare your variable as House (e.g.var house:House?
)
制定协议(例如
Buildable
)。让你所有的房子都实施它。将你的变量声明为 Buildable(例如var house:Buildable?
- 注意?
,所以你不必初始化它,它可能是 nil) - 这通常是我会怎么做,试图避免继承创建一个类(例如
House
)。把所有的房子(House1
,House2
,等)继承形式House
。将您的变量声明为 House(例如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.
声明为Any
或AnyObject
可能有效,但它严重限制了您,在这种情况下这可能不是您想要做的。
And as an advice, try to grasp these basic principles before going forward and code.
作为建议,在继续编写代码之前,请尝试掌握这些基本原则。