如何在Swift中创建一个返回符合协议的类型的函数?
如何在Swift中创建一个返回符合协议的类型的函数 这是我现在正在尝试的,但它显然不会像这样编译如何在Swift中创建一个返回符合协议的类型的函数?,swift,protocols,Swift,Protocols,如何在Swift中创建一个返回符合协议的类型的函数 这是我现在正在尝试的,但它显然不会像这样编译 struct RoutingAction { enum RoutingActionType{ case unknown(info: String) case requestJoinGame(gameName: String) case requestCreateGame(gameName: String) case respon
struct RoutingAction {
enum RoutingActionType{
case unknown(info: String)
case requestJoinGame(gameName: String)
case requestCreateGame(gameName: String)
case responseJoinGame
case responseCreateGame
}
// Any.Type is the type I want to return, but I want to specify that it will conform to MyProtocol
func targetType() throws -> Any.Type:MyProtocol {
switch self.actionType {
case .responseCreateGame:
return ResponseCreateGame.self
case .responseJoinGame:
return ResponseJoinGame.self
default:
throw RoutingError.unhandledRoutingAction(routingActionName:String(describing: self))
}
}
}
我个人更喜欢返回实例而不是类型,但你也可以这样做。以下是实现这一目标的一种方法:
protocol MyProtocol:class
{
init()
}
class ResponseCreateGame:MyProtocol
{
required init() {}
}
class ResponseJoinGame:MyProtocol
{
required init() {}
}
enum RoutingActionType
{
case unknown(info: String),
requestJoinGame(gameName: String),
requestCreateGame(gameName: String),
responseJoinGame,
responseCreateGame
// Any.Type is the type I want to return, but I want to specify that it will conform to MyProtocol
var targetType : MyProtocol.Type
{
switch self
{
case .responseCreateGame:
return ResponseCreateGame.self as MyProtocol.Type
case .responseJoinGame:
return ResponseJoinGame.self as MyProtocol.Type
default:
return ResponseJoinGame.self as MyProtocol.Type
}
}
}
let join = RoutingActionType.responseJoinGame
let objectType = join.targetType
let object = objectType.init()
请注意,您的协议需要强制使用必需的init(),以允许使用返回的类型创建实例。注2:为了使测试更简单,我对结构做了一些修改,但我相信您可以根据需要调整此示例。为什么不使用simple:
func targetType() throws -> MyProtocol
?
编辑:
我想你不能。因为如果您返回类型,实际上您返回了类的一个实例,它不能符合您的协议。此运行时的功能是从objective-c继承的。您可以看到SwiftObject类。为什么要这样做?为什么不返回一个表示响应类型的枚举值呢?我需要使用该类型创建一个对象。我已经有一个表示响应类型的枚举。我想为相应的枚举值创建正确类型的实例。这将返回符合
MyProtocol
的实例,而不是符合MyProtocol