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

时间:2017-07-10 01:53:40

标签: swift protocols

如何在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 个答案:

答案 0 :(得分:3)

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

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:我稍微改变了结构以使我的测试更容易,但我相信你能够根据自己的需要调整这个样本。

答案 1 :(得分:0)

为什么你不想使用简单的:

func targetType() throws -> MyProtocol

修改

我想你不能。因为如果您实际返回Type,则返回类Class的实例,并且它无法符合您的协议。此运行时的功能继承自objective-c。你可以看到SwiftObject类。