说所有擦除类型都是不可初始化的是否正确?
Is it correct to say all erased types are non-initializable?
(我所说的擦除类型是指:(Any
、AnyHashable
、AnyObject
)、protocol
或根 class NSObject
).
我问这个问题是因为在下面的代码中我无法将 something
初始化为 AnyObject
。我收到错误:
cannot invoke initializer for type 'AnyObject?' with no arguments
我正在寻找合适的解决方法。我不认为正确的选择是在每个语句中初始化 something
...
func returnObject() -> AnyObject{
var something = AnyObject()
if x == someProperty{
something = y
}
else if x == anotherProperty{
something = z
}else{
something = t
}
return something
}
您希望初始化做什么?如果您打算立即用 y
、z
或 t
覆盖 something
,这有什么关系?
func returnObject() -> AnyObject {
let something: AnyObject
if x == someProperty{
something = y
}
else if x == anotherProperty{
something = z
}
else{
something = t
}
return something
}
但是,使用 switch
:
更简洁
func returnObject() -> AnyObject {
let something: AnyObject
switch x {
case someProperty: something = y
case anotherProperty: something = z
default: something = t
}
return something
}
如果您只是返回 something
,您可以直接将其内联:
func returnObject() -> AnyObject {
switch x {
case someProperty: return y
case anotherProperty: return z
default: return t
}
}
(我所说的擦除类型是指:(Any
、AnyHashable
、AnyObject
)、protocol
或根 class NSObject
).
我问这个问题是因为在下面的代码中我无法将 something
初始化为 AnyObject
。我收到错误:
cannot invoke initializer for type 'AnyObject?' with no arguments
我正在寻找合适的解决方法。我不认为正确的选择是在每个语句中初始化 something
...
func returnObject() -> AnyObject{
var something = AnyObject()
if x == someProperty{
something = y
}
else if x == anotherProperty{
something = z
}else{
something = t
}
return something
}
您希望初始化做什么?如果您打算立即用 y
、z
或 t
覆盖 something
,这有什么关系?
func returnObject() -> AnyObject {
let something: AnyObject
if x == someProperty{
something = y
}
else if x == anotherProperty{
something = z
}
else{
something = t
}
return something
}
但是,使用 switch
:
func returnObject() -> AnyObject {
let something: AnyObject
switch x {
case someProperty: something = y
case anotherProperty: something = z
default: something = t
}
return something
}
如果您只是返回 something
,您可以直接将其内联:
func returnObject() -> AnyObject {
switch x {
case someProperty: return y
case anotherProperty: return z
default: return t
}
}