Rah*_*iya 73 generics ios swift swift-protocols swift2
我有一个协议RequestType,它有关联类型模型,如下所示.
public protocol RequestType: class {
associatedtype Model
var path: String { get set }
}
public extension RequestType {
public func executeRequest(completionHandler: Result<Model, NSError> -> Void) {
request.response(rootKeyPath: rootKeyPath) { [weak self] (response: Response<Model, NSError>) -> Void in
completionHandler(response.result)
guard let weakSelf = self else { return }
if weakSelf.logging { debugPrint(response) }
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我正在尝试为所有失败的请求排队.
public class RequestEventuallyQueue {
static let requestEventuallyQueue = RequestEventuallyQueue()
let queue = [RequestType]()
}
Run Code Online (Sandbox Code Playgroud)
但我得到的错误是let queue = [RequestType](),Protocol RequestType只能用作通用约束,因为它具有Self或associatedType要求.
Sco*_*son 119
假设我们暂时调整您的协议以添加使用相关类型的例程:
public protocol RequestType: class {
associatedtype Model
var path: String { get set }
func frobulateModel(aModel: Model)
}
Run Code Online (Sandbox Code Playgroud)
Swift让你创建一个RequestType你想要的阵列.我可以将这些请求类型的数组传递给函数:
func handleQueueOfRequests(queue: [RequestType]) {
// frobulate All The Things!
for request in queue {
request.frobulateModel(/* What do I put here? */)
}
}
Run Code Online (Sandbox Code Playgroud)
我明白了我想要讨论所有的事情,但我需要知道要传递给调用的参数类型.我的一些RequestType实体可以拿a LegoModel,有些可以拿a PlasticModel,而其他人可以拿a PeanutButterAndPeepsModel.Swift对歧义不满意,所以它不会让你声明一个具有相关类型的协议的变量.
同时,例如,RequestType当我们知道所有人都使用它时,创建一个数组是完全合理的LegoModel.这似乎是合理的,但是,你需要某种方式来表达这一点.
一种方法是创建一个类(或结构,或枚举),将真实类型与抽象模型类型名称相关联:
class LegoRequestType: RequestType {
typealias Model = LegoModel
// Implement protocol requirements here
}
Run Code Online (Sandbox Code Playgroud)
现在声明一个数组是完全合理的,LegoRequestType因为如果我们想要frobulate所有这些,我们就知道LegoModel每次都要传入.
关联类型的这种细微差别使得任何使用它们的协议都很特殊.Swift标准库最像这样的协议Collection或者Sequence.
为了允许您创建实现Collection协议的事物数组或实现序列协议的一组事物,标准库使用称为"类型擦除"的技术来创建结构类型AnyCollection<T>或AnySequence<T>.类型擦除技术在Stack Overflow答案中解释相当复杂,但是如果你在网上搜索有很多关于它的文章.
我可以在YouTube 上推荐Alex Gallagher关于协议类型协议(PAT)的视频.
Moj*_*ini 29
您可以使用不透明的结果类型来实现类似的目标。
想象一下:
protocol ProtocolA {
associatedtype number
}
class ClassA: ProtocolA {
typealias number = Double
}
Run Code Online (Sandbox Code Playgroud)
所以下面会产生错误:
var objectA: ProtocolA = ClassA() /* Protocol can only be used as a generic constraint because it has Self or associatedType requirements */
Run Code Online (Sandbox Code Playgroud)
但是通过在类型之前添加关键字来使类型不透明some将解决问题,通常这是我们唯一想要的:
var objectA: some ProtocolA = ClassA()
Run Code Online (Sandbox Code Playgroud)
在以下情况下也可能会出现此错误:
protocol MyProtocol {
assosciatedtype SomeClass
func myFunc() -> SomeClass
}
struct MyStuct {
var myVar = MyProtocol
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,解决问题所需要做的就是使用泛型:
protocol MyProtocol {
assosciatedtype SomeClass
func myFunc() -> SomeClass
}
struct MyStuct<T: MyProtocol> {
var myVar = T
}
Run Code Online (Sandbox Code Playgroud)
如何通过实现关联类型和基本协议来使用通用协议的示例:
import Foundation
protocol SelectOptionDataModelProtocolBase: class{}
protocol SelectOptionDataModelProtocol: SelectOptionDataModelProtocolBase {
associatedtype T
var options: Array<T> { get }
var selectedIndex: Int { get set }
}
class SelectOptionDataModel<A>: SelectOptionDataModelProtocol {
typealias T = A
var options: Array<T>
var selectedIndex: Int
init(selectedIndex _selectedIndex: Int, options _options: Array<T>) {
self.options = _options
self.selectedIndex = _selectedIndex
}
}
Run Code Online (Sandbox Code Playgroud)
和一个示例视图控制器:
import UIKit
struct Car {
var name: String?
var speed: Int?
}
class SelectOptionViewController: UIViewController {
// MARK: - IB Outlets
// MARK: - Properties
var dataModel1: SelectOptionDataModelProtocolBase?
var dataModel2: SelectOptionDataModelProtocolBase?
var dataModel3: SelectOptionDataModelProtocolBase?
// MARK: - Initialisation
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init() {
self.init(title: "Settings ViewController")
}
init(title _title: String) {
super.init(nibName: nil, bundle: nil)
self.title = _title
self.dataModel1 = SelectOptionDataModel<String>(selectedIndex: 0, options: ["option 1", "option 2", "option 3"])
self.dataModel2 = SelectOptionDataModel<Int>(selectedIndex: 0, options: [1, 2, 3])
self.dataModel3 = SelectOptionDataModel<Car>(selectedIndex: 0, options: [Car(name: "BMW", speed: 90), Car(name: "Toyota", speed: 60), Car(name: "Subaru", speed: 120)])
}
// MARK: - IB Actions
// MARK: - View Life Cycle
}
Run Code Online (Sandbox Code Playgroud)
anySwift 5.7 中的存在主义我们现在可以通过简单地在调用站点使用关键字来解决“此协议不能用作通用约束,因为它有Self或要求”:associatedTypeany
let queue = [any RequestType]()
Run Code Online (Sandbox Code Playgroud)
Xcode 14 现在建议将此更改作为修复程序,并且错误消失了!
any目前,泛型比存在性的功能更全面、性能更佳,因此我们可能更喜欢使用存在性any,尽管它有其局限性。
为了更容易地使用正确的泛型语法,我们可以使用关键字some为具有单个泛型参数的函数指定泛型(这称为主关联类型)。
func addEntries1(_ entries: some Collection<MailmapEntry>, to mailmap: inout some Mailmap) {
for entry in entries {
mailmap.addEntry(entry)
}
}
func addEntries2(_ entries: any Collection<MailmapEntry>, to mailmap: inout any Mailmap) {
for entry in entries {
mailmap.addEntry(entry)
}
}
Run Code Online (Sandbox Code Playgroud)
对代码设计稍加改动就可以使之成为可能。在协议层次结构的顶部添加一个空的、非关联类型的协议。像这样...
public protocol RequestTypeBase: class{}
public protocol RequestType: RequestTypeBase {
associatedtype Model
var path: Model? { get set } //Make it type of Model
}
public class RequestEventuallyQueue {
static let requestEventuallyQueue = RequestEventuallyQueue()
var queue = [RequestTypeBase]() //This has to be 'var' not 'let'
}
Run Code Online (Sandbox Code Playgroud)
另一个例子,使用从协议 RequestType 派生的类,创建一个队列并将队列传递给一个函数以打印适当的类型
public class RequestA<AType>: RequestType{
public typealias Model = AType
public var path: AType?
}
public class RequestB<BType>: RequestType{
public typealias Model = BType
public var path: BType?
}
var queue = [RequestTypeBase]()
let aRequest: RequestA = RequestA<String>()
aRequest.path = "xyz://pathA"
queue.append(aRequest)
let bRequest: RequestB = RequestB<String>()
bRequest.path = "xyz://pathB"
queue.append(bRequest)
let bURLRequest: RequestB = RequestB<URL>()
bURLRequest.path = URL(string: "xyz://bURLPath")
queue.append(bURLRequest)
func showFailed(requests: [RequestTypeBase]){
for request in requests{
if let request = request as? RequestA<String>{
print(request.path!)
}else if let request = request as? RequestB<String>{
print(request.path!)
}else if let request = request as? RequestB<URL>{
print(request.path!)
}
}
}
showFailed(requests: queue)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32116 次 |
| 最近记录: |