How do I implement this protocol in struct

时间:2016-04-25 09:33:54

标签: swift design-patterns protocols abstract-factory

I'm new to Swift and I want to create an abstract factory for db access. Here is my protocol

protocol IDAOFactory
{
  associatedtype DAO: IDAO

  func createAccountDAO<DAO: IAccountDAO>() -> DAO
}

struct RealmFactory: IDAOFactory
{

}

protocol IDAO
{
   associatedtype T
   func save(object: T)
}

protocol IAccountDAO : IDAO
{

}

struct AccountDAORealm: IAccountDAO
{

}

How to implement the IDAOFactory in struct RealmFactory and IAccountDAO in struct AccountDAORealm? Can anybody help?

1 个答案:

答案 0 :(得分:2)

Swift中的泛型具有许多限制,特别是在协议中使用并在struct中实现时。让我们等到Swift 3:)

我使用协议和派生类或泛型与类,但混合协议泛型和结构在Swift 2(C#泛型更方便)中令人头疼

我在游乐场玩你的代码,这里是

protocol IDAOFactory
{
    associatedtype DAO: IDAO

    func createAccountDAO<DAO: IAccountDAO>() -> DAO
}

protocol IDAO
{
    init()
    associatedtype T
    func save(object: T)
}

protocol IAccountDAO : IDAO
{
    init()
}

public class AccountDAORealm: IAccountDAO
{
    var data: String = ""

    required public init() {
        data = "data"
    }

    func save(object: AccountDAORealm) {
        //do save
    }
}

let accountDAORealm = AccountDAORealm() 
//As you see accountDAORealm is constructed without any error

struct RealmFactory: IDAOFactory
{
    func createAccountDAO<AccountDAORealm>() -> AccountDAORealm {
        return  AccountDAORealm() //but here constructor gives error
    }
}