如何在Swift中创建一个返回符合协议的类型的函数?

问题描述:

如何在Swift中创建一个返回符合协议的类型的函数?如何在Swift中创建一个返回符合协议的类型的函数?

这是我现在正在尝试,但它显然不会像这样编译。

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)) 
     } 
    } 
} 
+2

你为什么要这么做?为什么不只是返回一个代表响应类型的枚举值? – nathan

+0

我需要使用Type来创建一个对象。 –

+0

我已经有一个代表响应类型的枚举。我想为相应的枚举值创建正确类型的实例。 –

我个人更喜欢返回一个实例,而不是一个类型,但你也可以这样做。下面是实现这一目标的一种方法:

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:为了让我的测试更容易,我改变了一点结构,但我相信您可以根据自己的需要调整此示例。

为什么你不希望使用简单:

func targetType() throws -> MyProtocol 

编辑:

我认为你不能。因为如果返回类型实际上你返回一个Class类的实例,并且它不能符合你的协议。该运行时的功能是从objective-c继承的。你可以看到SwiftObject类。

+0

这将返回一个符合'MyProtocol'的实例,而不是符合'MyProtocol'的类型 –

+0

我编辑了答案 –