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.
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>()