我想创建一个方法的协议,它接受通用输入并返回一个通用值。
这是我试过迄今为止,但它会产生语法错误。
Use of undeclared identifier T.
我究竟做错了什么?
protocol ApiMapperProtocol { func MapFromSource(T) -> U } class UserMapper: NSObject,ApiMapperProtocol { func MapFromSource(data: NSDictionary) -> UserModel { var user = UserModel() as UserModel var accountsData:NSArray = data["Accounts"] as NSArray return user } }
对于协议有点不同。看看“关联类型”
in Apple’s documentation。
这是你在你的例子中使用它
protocol ApiMapperProtocol { associatedtype T associatedtype U func MapFromSource(T) -> U } class UserMapper: NSObject,ApiMapperProtocol { 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 } }