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?
答案 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
}
}