To clarify Lou Franco, answer a little: if you want to create a method that uses a specific ApiMapperProtocol , you do it like this:
protocol ApiMapperProtocol { associatedtype T associatedtype U func MapFromSource(T) -> U } class UserMapper: NSObject, ApiMapperProtocol { // these typealiases aren't required, but I'm including them for clarity // Normally, you just allow swift to infer them typealias T = NSDictionary typealias U = UserModel func MapFromSource(data: NSDictionary) -> UserModel { var user = UserModel() var accountsData:NSArray = data["Accounts"] as NSArray // For Swift 1.2, you need this line instead // var accountsData:NSArray = data["Accounts"] as! NSArray return user } } class UsesApiMapperProtocol { func usesApiMapperProtocol< SourceType, MappedType, ApiMapperProtocolType: ApiMapperProtocol where ApiMapperProtocolType.T == SourceType, ApiMapperProtocolType.U == MappedType>( apiMapperProtocol: ApiMapperProtocolType, source: SourceType) -> MappedType { return apiMapperProtocol.MapFromSource(source) } }
UsesApiMapperProtocol now guaranteed to accept only SourceType compatible with this ApiMapperProtocol :
let dictionary: NSDictionary = ... let uses = UsesApiMapperProtocol() let userModel: UserModel = uses.usesApiMapperProtocol(UserMapper() source: dictionary)
Heath Borders Mar 05 '15 at 3:56 2015-03-05 03:56
source share