简体   繁体   English

Swift 3中通用协议类型的变量

[英]Variable of generic protocol type in Swift 3

Is it possible to declare a variable with the type of a generic protocol in Swift? 在Swift中是否可以使用通用协议的类型声明变量?

If no, what are the alternatives? 如果没有,有哪些替代方案? It seems like a huge disadvantage that I cannot reuse a protocol with different type parameters, let alone mock it out. 我无法重用具有不同类型参数的协议,这似乎是一个巨大的缺点,更不用说对其进行模拟了。

Im not sure if this is what you mean, but you can do: 我不确定这是否是您的意思,但是您可以执行以下操作:

public typealias SuccessBlock<T> = (_ data: T) -> (Void)

and then define variables: 然后定义变量:

var myBlock: SuccessBlock<String>

My workaround is non-generic protocol. 我的解决方法是非通用协议。 Agree about strange limitation thats hurts. 同意关于限制的多数民众赞成在伤害。 Limitation due to missing associatedtype is must use base of element in protocol, all other internal can be used with generic type 由于缺少关联类型而造成的限制必须在协议中使用元素的基础,所有其他内部都可以与泛型一起使用

//: Playground - noun: a place where people can play

import UIKit
import Foundation

class Item: NSObject {

}

protocol Datasource {

    subscript(index: Int) -> NSObjectProtocol? { get }
}

class BaseDatasource<Element: NSObjectProtocol>: Datasource {

    private(set) var data: [Element]?

    subscript(index: Int) -> NSObjectProtocol? {
        get {
            return data?[index]
        }
    }

    func sortedData(_ data: [Element]) -> [Element] {
        return data
    }
}

class ItemsDatasource: BaseDatasource<Item> {
    ///some specific code
}

var dataOfInts: Datasource?

dataOfInts = ItemsDatasource()//or BaseDatasource<Item>()

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

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