如何在 Swift 中创建通用协议? [英] How to create generic protocols in Swift?

查看:47
本文介绍了如何在 Swift 中创建通用协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个方法创建一个协议,该方法接受一个通用输入并返回一个通用值.

I'd like to create a protocol with a method that takes a generic input and returns a generic value.

这是我迄今为止尝试过的,但它产生了语法错误.

This is what I've tried so far, but it produces the syntax error.

使用未声明的标识符 T.

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
    } 
}

推荐答案

协议有点不同.查看关联类型"在 Apple 文档中.

It's a little different for protocols. Look at "Associated Types" in Apple's documentation.

这就是您在示例中使用它的方式

This is how you use it in your example

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
    }
}

这篇关于如何在 Swift 中创建通用协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆