Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement this protocol in struct

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?

like image 856
Mike Lu Avatar asked Jan 22 '26 06:01

Mike Lu


1 Answers

Generics in Swift have many restrictions especially when used in protocols and implemented in struct. Let's wait until Swift 3 :)

I use protocols and derived classes or generics with classes but mixing protocols generics and structs makes a headache in Swift 2 (C# generics in much more convenient)

I played with your code in playground, here it is

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
    }
}
like image 178
Andriy Zymenko Avatar answered Jan 23 '26 19:01

Andriy Zymenko