1
votes

I'm writing a service that gets objects from a database. All of those entities in Swift conform to a protocol DAO, to make the get function reusable. I want to add a method to the protocol that accepts a dictionary and returns the object type.

Is it possible to write a static protocol method that returns the specialized classes type?

The code below (roughly) illustrates what I'm trying to do.

protocol DAO {
    static func fromDictionary(_ dictionary: [String : Any]) -> T // ??
}

class User : DAO {

    init(_ dictionary: [String : Any]) {
        ...
    }


    static func fromDictionary(_ dictionary: [String : Any]) -> User {
        return User(dictionary)
    }
}

class DataService<T> where T: DAO {

    func get(id: String) -> T {
        let dictionary = API.get(id)
        return T.fromDictionary(dictionary)
    }
}

class ViewController : UIViewController {

    let dataService: DataService<User>
    let user: User

    override func viewDidLoad() {
        super.viewDidLoad()
        dataService = DataService<User>()
        user = dataService.get(id: "abcdefg")
    }

}

1
You can make the return type Self - dan

1 Answers

2
votes

You can use AssociatedTypes in your protocol definition.

protocol DAO {
    associatedtype Item
    static func fromDictionary(_ dictionary: [String : Any]) -> Item
}

class User : DAO {

    static func fromDictionary(_ dictionary: [String : Any]) -> User {
         return User(dictionary)
    }
}

Read the official docs for AssociatedTypes