Return 符合 swift 协议的 class (实际的 class,不是它的实例)
Return a class that conforms to a swift protocol (the actual class, not an instance of it)
我无法返回 class 而不是它符合协议的实例。那是可能做的事吗?这是我的代码的近似值:
public protocol MyProt {
//things
}
var protConformer: MyProt {
return boolVar ? ClassOne : ClassTwo // where both classes conform to MyProt
}
当然,我在这里得到一个错误说 "Cannot convert return expression of type 'ClassOne.Type' to return type 'MyProt'
。关于这是否可能的任何想法?
您需要将protConformer
的类型更改为协议的元类型,即MyProt.Type
,如果您想要return一个type 符合协议而不是这种类型的实例。
var protConformer: MyProt.Type {
return boolVar ? ClassOne.self : ClassTwo.self
}
类型 MyProt 的意思是 "an instance of a type that adopts MyProt." 如果你真的想操作元类型,语法是:
var protConformer: MyProt.Type {
return boolVar ? ClassOne.self : ClassTwo.self
}
但我必须警告你,这几乎从来都不是正确的做法。您可能正在寻找通用的这里(无论您的现实生活中的问题是什么)。
我无法返回 class 而不是它符合协议的实例。那是可能做的事吗?这是我的代码的近似值:
public protocol MyProt {
//things
}
var protConformer: MyProt {
return boolVar ? ClassOne : ClassTwo // where both classes conform to MyProt
}
当然,我在这里得到一个错误说 "Cannot convert return expression of type 'ClassOne.Type' to return type 'MyProt'
。关于这是否可能的任何想法?
您需要将protConformer
的类型更改为协议的元类型,即MyProt.Type
,如果您想要return一个type 符合协议而不是这种类型的实例。
var protConformer: MyProt.Type {
return boolVar ? ClassOne.self : ClassTwo.self
}
类型 MyProt 的意思是 "an instance of a type that adopts MyProt." 如果你真的想操作元类型,语法是:
var protConformer: MyProt.Type {
return boolVar ? ClassOne.self : ClassTwo.self
}
但我必须警告你,这几乎从来都不是正确的做法。您可能正在寻找通用的这里(无论您的现实生活中的问题是什么)。