【问题标题】:Variable of generic protocol type in Swift 3Swift 3 中通用协议类型的变量
【发布时间】:2016-10-17 11:50:57
【问题描述】:

是否可以在 Swift 中声明具有泛型协议类型的变量?

如果没有,有什么替代方案?我无法重用具有不同类型参数的协议,更不用说模拟它,这似乎是一个巨大的缺点。

【问题讨论】:

标签: swift generics swift-protocols


【解决方案1】:

我不确定这是否是您的意思,但您可以这样做:

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

然后定义变量:

var myBlock: SuccessBlock<String>

【讨论】:

  • 当然,但这不是接口。它只是一个类型别名。
【解决方案2】:

我的解决方法是非通用协议。 同意奇怪的限制,这很痛苦。 由于缺少关联类型的限制是必须使用协议中元素的基础,所有其他内部都可以与泛型类型一起使用

//: 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>()

【讨论】:

    猜你喜欢
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    相关资源
    最近更新 更多