简体   繁体   中英

Variable of generic protocol type in Swift 3

Is it possible to declare a variable with the type of a generic protocol in 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>()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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