简体   繁体   English

Swift 通用协议

[英]Swift Generic Protocol

Is it possible to have a generic protocol in swift?是否有可能在 swift 中有一个通用协议? I tried protocol foo<T>{} and that is not legal.我尝试了protocol foo<T>{}并且这是不合法的。 I'm looking for something that can be used similarly to Java's List<T> interface.我正在寻找可以类似于 Java 的List<T>接口使用的东西。

There is no such thing as generics for protocols.没有协议的泛型这样的东西。 But there is something else, which ressembles a lot to the generics when you look at it.但是还有一些其他东西,当您查看它时,它与泛型非常相似。

Here is an example taken from the Swift standard library:下面是一个取自 Swift 标准库的示例:

protocol Generator {
    typealias Element
    func next() -> Element?
}

The Swift book scratches the surface in the Generics chapter, Associated Types. Swift 书在泛型一章关联类型中触及了皮毛。

It's possible to achieve the same functionality of a Java List Interface in Swift using a protocol with an associated type declaration.使用带有关联类型声明的协议,可以在 Swift 中实现与 Java 列表接口相同的功能。

//  Created by Juan Miguel Pallares Numa on 2/24/20.
//  Copyright © 2020 Juan Miguel Pallares Numa. All rights reserved.

import Foundation

protocol List {

    // An associated type gives a placeholder name to a type
    // that is used as part of the protocol.
    associatedtype Element

    func add(index: Int, element: Element)
    func get(index: Int) -> Element
}

class ArrayList<Element>: List {

    private var items: [Element] = []

    func add(index: Int, element: Element) {
        items.insert(element, at: index)
    }

    func get(index: Int) -> Element {
        return items[index]
    }
}

let arrayOfInts = ArrayList<Int>()
let arrayOfStrings = ArrayList<String>()

arrayOfInts.add(index: 0, element: 17)
arrayOfInts.add(index: 1, element: 19)
print("arrayOfInts[1] is \(arrayOfInts.get(index: 1))")
// arrayOfInts[1] is 19

arrayOfStrings.add(index: 0, element: "Generics - The Swift Programming Language")
print("arrayOfStrings[0] is \(arrayOfStrings.get(index: 0))")
// arrayOfStrings[0] is Generics - The Swift Programming Language

/* (lldb) expr print(arrayOfInts.items)
[17, 19]
(lldb) expr print(arrayOfStrings.items)
["Generics - The Swift Programming Language"] */

The documentation speaks best for itself.文档本身最能说明问题。 Please see Associated Types in https://docs.swift.org/swift-book/LanguageGuide/Generics.html#ID189请参阅https://docs.swift.org/swift-book/LanguageGuide/Generics.html#ID189 中的关联类型

Probably you can refer to my answer: https://stackoverflow.com/a/54900296/3564632 可能你可以参考我的答案: https//stackoverflow.com/a/54900296/3564632

What you might need to do apart from having associatedtype in protocol is to actually have a generic class in the middle that acts as your generic interface (kind of java). 除了在协议中具有关联类型之外,您可能需要做的是实际上在中间有一个泛型类作为您的通用接口(一种java)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM