如何在Swift中创建通用协议?

前端之家收集整理的这篇文章主要介绍了如何在Swift中创建通用协议?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想创建一个方法的协议,它接受通用输入并返回一个通用值。

这是我试过迄今为止,但它会产生语法错误

Use of undeclared identifier T.

我究竟做错了什么?

  1. protocol ApiMapperProtocol {
  2. func MapFromSource(T) -> U
  3. }
  4.  
  5. class UserMapper: NSObject,ApiMapperProtocol {
  6. func MapFromSource(data: NSDictionary) -> UserModel {
  7. var user = UserModel() as UserModel
  8. var accountsData:NSArray = data["Accounts"] as NSArray
  9. return user
  10. }
  11. }
对于协议有点不同。看看“关联类型” in Apple’s documentation

这是你在你的例子中使用它

  1. protocol ApiMapperProtocol {
  2. associatedtype T
  3. associatedtype U
  4. func MapFromSource(T) -> U
  5. }
  6.  
  7. class UserMapper: NSObject,ApiMapperProtocol {
  8. typealias T = NSDictionary
  9. typealias U = UserModel
  10.  
  11. func MapFromSource(data:NSDictionary) -> UserModel {
  12. var user = UserModel()
  13. var accountsData:NSArray = data["Accounts"] as NSArray
  14. // For Swift 1.2,you need this line instead
  15. // var accountsData:NSArray = data["Accounts"] as! NSArray
  16. return user
  17. }
  18. }

猜你在找的Swift相关文章