协议只能用作通用约束,因为它具有Self或associatedType要求

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)的视频.

  • "你的解决方案非常通用*" (29认同)
  • 这个答案是一个很好的借口来阻止“frobulate”这个词的使用。 (6认同)
  • 这是我在这个问题上看到的最好的解释之一 (5认同)
  • *flobulate* 是什么意思? (3认同)
  • 20 世纪 80 年代出现了一款文字冒险游戏系列,始于 Zork 游戏。在该系列游戏中,有 Frobozz Magic Company。他们过去常把事情搞得一团糟。简而言之,这是一个愚蠢的短语,用于描述不具体的动作。 (3认同)
  • 这么好的解释,这么单一的答案。 (2认同)

Moj*_*ini 29

从 Swift 5.1 - Xcode 11

您可以使用不透明的结果类型来实现类似的目标。

想象一下:

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)


Lew*_*ski 9

在以下情况下也可能会出现此错误:

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)


Tim*_*Dev 8

斯威夫特 5.1

如何通过实现关联类型基本协议来使用通用协议示例

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)


Pra*_*tti 7

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)


Far*_*had 5

对代码设计稍加改动就可以使之成为可能。在协议层次结构的顶部添加一个空的、非关联类型的协议。像这样...

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)