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?
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.