Why can i make same-type requirement in swift with generics? Is there any way? - swift

Ok so i have some class defined like this:
public final class Process<InputType, OutputType, Memory>
And i want to make the function available only for case when InputType and
OutputType are exactly same type.
So i tried like this like this:
extension Process where InputType == OutputType { }
But this would result in:
Same-type requirement makes generic parameters InputType and
OutputType equivalent
So then i've gone a bit far and tried to do it like this:
func bypass<SameType>() -> Process<SameType, SameType, Memory> where OutputType == InputType {}
But this would result in exactly same error.
So the question is why can't i define generics in such way that two generic types would be Equivalent, cause that's exactly what i wanted. I wanted to define function available only for this case, that would fail at compile time if this rule is not followed.
So right now i'm using something like this:
public static func bypass<SameType>() -> Process<SameType, SameType, Memory>
Which would ultimately fail only at runtime and not even when created but when the concrete class is triggered for action.
Is there any way to define extension or function for generic parameters of same type that would just not compile(result in compile time error)?
Update: some details of implementations are missed cause would make code unreadable and they are not critical for the context

In Swift 4 and later, you can write:
public final class Process<InputType, OutputType, Memory> {
// ...
}
extension Process where InputType == OutputType {
func bypass() -> Process<InputType, OutputType, Memory> {
// ...
}
}
Original answer (Swift 3):
You can't constraint types on generic classes yet even though some changes are coming in Swift 4. However, you can constraint types on a protocol. You can make a protocol that only Process conforms to like this:
protocol ProcessProtocol {
// I haven't found a way to name these associated type identically to
// those in the class. If anyone discover a way, please let me know
associatedtype IT
associatedtype OT
associatedtype MT
}
final public class Process<InputType, OutputType, MemoryType>: ProcessProtocol {
typealias IT = InputType
typealias OT = OutputType
typealias MT = MemoryType
// your code
}
// Note that this is an extension on the protocol, not the class
extension ProcessProtocol where IT == OT {
func foo() {
// this function is only available when InputType = OutputType
}
}

Related

Swift Generics - Attempting to make a generic protocol concrete fails when attempting to use specialised sub-protocol as variable

I want to know why my SomeResourceRepository is still generic, even though it is only defined in one case only, which is when I set ResourceType = SomeResource, which XCode formats as below with the where clause. Code below which shows the exact setup I'm trying to achieve, written in a Playground.
I am trying to define a generic protocol for any given ResourceType such that the ResourceTypeRepository protocol then automatically requires the same set of functions, without having to copy-paste most of GenericRepository only to manually fill in the ResourceType for each Repository I make. The reason I need this as a protocol is because I want to be able to mock this for testing purposes later. So I'll provide an implementation of said protocol somewhere else in the actual app.
My interpretation of the code below is that it should work, because both SomeResourceLocalRepository and SomeResourceRemoteRepository are concrete, as I have eliminated the associated type by defining them "on top of" SomeResourceRepository, which is only defined where ResourceType == SomeResource.
import Foundation
struct SomeResource: Identifiable {
let id: String
let name: String
}
struct WhateverResource: Identifiable {
let id: UUID
let count: UInt
}
protocol GenericRepository: class where ResourceType: Identifiable {
associatedtype ResourceType
func index() -> Array<ResourceType>
func show(id: ResourceType.ID) -> ResourceType?
func update(resource: ResourceType)
func delete(id: ResourceType.ID)
}
protocol SomeResourceRepository: GenericRepository where ResourceType == SomeResource {}
protocol SomeResourceLocalRepository: SomeResourceRepository {}
protocol SomeResourceRemoteRepository: SomeResourceRepository {}
class SomeResourceLocalRepositoryImplementation: SomeResourceLocalRepository {
func index() -> Array<SomeResource> {
return []
}
func show(id: String) -> SomeResource? {
return nil
}
func update(resource: SomeResource) {
}
func delete(id: String) {
}
}
class SomeResourceService {
let local: SomeResourceLocalRepository
init(local: SomeResourceLocalRepository) {
self.local = local
}
}
// Some Dip code somewhere
// container.register(.singleton) { SomeResourceLocalRepositoryImplementation() as SomeResourceLocalRepository }
Errors:
error: Generic Protocols.xcplaygroundpage:45:16: error: protocol 'SomeResourceLocalRepository' can only be used as a generic constraint because it has Self or associated type requirements
let local: SomeResourceLocalRepository
^
error: Generic Protocols.xcplaygroundpage:47:17: error: protocol 'SomeResourceLocalRepository' can only be used as a generic constraint because it has Self or associated type requirements
init(local: SomeResourceLocalRepository) {
I will probably have to find another way to accomplish this, but it is tedious and quite annoying as we will produce a lot of duplicate code, and when we decide to change the API of our repositories, we will have to manually change it for all the protocols as we don't follow a generic "parent" protocol in this work-around.
I have read How to pass protocol with associated type as parameter in Swift and the related question found in an answer to this question, as well as Specializing Generic Protocol and others.
I feel like this should work, but it does not. The end goal is a concrete protocol that can be used for dependency injection, e.g. container.register(.singleton) { ProtocolImplementation() as Protocol } as per Dip - A simple Dependency Injection Container, BUT without copy-pasting when the protocol's interface clearly can be made generic, like in the above.
As swift provides a way to declare generic protocols (using associatedtype keyword) it's impossible to declare a generic protocol property without another generic constraint. So the easiest way would be to declare resource service class generic - class SomeResourceService<Repository: GenericRepository>.
But this solution has a big downside - you need to constraint generics everywhere this service would be involved.
You can drop generic constraint from the service declaration by declaring local as a concrete generic type. But how to transit from generic protocol to the concrete generic class?
There's a way. You can define a wrapper generic class which conforms to GenericRepository. It does not really implements its methods but rather passes to an object (which is real GenericRepository) it wraps.
class AnyGenericRepository<ResourceType: Identifiable>: GenericRepository {
// any usage of GenericRepository must be a generic argument
init<Base: GenericRepository>(_ base: Base) where Base.ResourceType == ResourceType {
// we cannot store Base as a class property without putting it in generics list
// but we can store closures instead
indexGetter = { base.index() }
// and same for other methods or properties
// if GenericRepository contained a generic method it would be impossible to make
}
private let indexGetter: () -> [ResourceType] {
indexGetter()
}
// ... other GenericRepository methods
}
So now we have a concrete type which wraps real GenericRepository. You can adopt it in SomeResourceService without any alarm.
class SomeResourceService {
let local: AnyGenericRepository<SomeResource>
}

How to define a Swift protocol that enforces its adopters themselves to conform to an associated type?

I need to work with objects that not only conform to a protocol, but also expose the type of a second protocol which they conform to. (This is for use with NSXPCConnection, where you must configurable not only an object to proxy, but also tell it which protocol should be exposed on that proxied object.)
I tried something like:
protocol Conformer where Self : Conformer.P {
associatedtype P : Protocol
static var interface : P {get}
init(info: String)
}
func exposeOverXPC<T:Conformer>(_ _: T.Type) {
let c : NSXPCConnection = …
c.exportedInterface = NSXPCInterface(with: T.interface)
c.exportedObject = T(info:"foo")
}
But it results in an error:
Associated type 'P' can only be used with a concrete type or generic parameter base
Specifically I want exposeOverXPC to only accept objects that:
Are initializeable in a particular way
Have a static property interface which references a protocol
Are themselves conformant to said interface
It's the last step that I'm getting stuck on, is there any way I can accomplish it?
You cannot restrict who conforms to a protocol, that goes against the concept of having protocols in the first place if you think about it. However you can use composed types, Swift4 feature, in your generic parameter in exposeOverXPC.
protocol Interface {
}
protocol XPCExposable {
associatedtype P: Interface
init(info: String)
static var interface: P { get }
}
func exposeOverXPC<T: XPCExposable & Interface>(_ : T.Type) {
// 1: T is initializeable in a particular way
// 2: Has a static property interface which references a protocol
// 3: Are themselves conformant to said interface
}
Yes this constraints T to conform to Interface and not P, your best bet is to make exposeOverXPC private/internal and provide APIs that expect Interface subtype. wherever you have access to the Interface subtype expose that api. e.g:
Solution 1
protocol InterfaceSubType: Interface {
fun test()
}
/// Create as many `API`s as the number of `Interface` subtypes you have.
func exposeOverXPC<T: XPCExposable & InterfaceSubType>(_ : T.Type) {
exposeOverXPC(T.self)
}
/// set to private, you only want to expose the APIs with `Interface` subtype.
private func exposeOverXPC<T: XPCExposable & Interface>(_ : T.Type) {
// Impl.
}
Solution 2
An alternative solution to have a function with parameters whose type is the associated type is to add that api (as static function if you wish) by extending the protocol. You must know all the expected subtypes of Interface in this extension.
extension XPCExposable {
static func exposeOverXPC<T>(_ interface: P, _ xpcType: T.Type) where T: XPCExposable {
// Expected subtype Interface
if let subInterface = interface as? InterfaceSubType {
subInterface.test()
}
// Other subtypes here.
}
}
Can be called as:
let impl = Impl(info: "")
Impl.exposeOverXPC(Impl.interface, Impl.self)
Its an extension on XPCExposable so you constrain the caller to be a conformer and the parameter requires XPCExposable.P so you're all set.
Downsides of this solution are:
You have two parameters instead of one.
It uses if conditions, I don't know if thats worth mentioning as downside other than that I'd like to push the first solution as favourite.

Generics Protocol as Type in Swift

How I can create a protocol variable. My goal is a protocol will be have a function with a generic type and I'm using associatedtype which is accessing to Class and the function will be return generic type. Example declaration below:
public protocol ComponentFactory {
associatedtype T // A class and that class can be inherit from another so I need define generic type here
func create() -> T
}
I want to declare a variable for this protocol like that:
fileprivate var mComponentFactoryMap = Dictionary<String, ComponentFactory>()
At this line I receive a error:
Protocol 'ComponentFactory' can only be used as a generic constraint because it has Self or associated type requirements
I see from Android, actually from kotlin they have a declare for interface like:
private val mComponentFactoryMap = mutableMapOf<String, ComponentFactory<*>>()
Any guys can help me, how I can declare this from Swift?
I've solved this from few months ago with descriptions below. Please check it and give me another solution if you have.
Firstly, make some change for Protocol. At associatedtype T should be change to associatedtype Component and Component is a class which will be inherited from another class (important step).
public protocol ProComponentFactory {
associatedtype Component
func create() -> Component?
}
Second, I will make a Generic Struct with inheritance from ProComponentFactory:
public struct ComponentFactory<T>: ProComponentFactory {
public typealias Component = T
public func create() -> T? { return T.self as? T }
}
Well done, for now you can define a variable as I example in my question above:
fileprivate var mComponentFactoryMap = Dictionary<String, ComponentFactory<Component>>()
As well for any class was inherit from Component and variable mComponentFactoryMap can using extension inside.

Statically typed properties in Swift protocols

I'm trying to use Protocol-Oriented Pgrogramming for model layer in my application.
I've started with defining two protocols:
protocol ParseConvertible {
func toParseObject() -> PFObject?
}
protocol HealthKitInitializable {
init?(sample: HKSample)
}
And after implementing first model which conforms to both I've noticed that another model will be basically similar so I wanted to create protocol inheritance with new one:
protocol BasicModel: HealthKitInitializable, ParseConvertible {
var value: AnyObject { get set }
}
A you can see this protocol has one additional thing which is value but I want this value to be type independent... Right now I have models which use Double but who knows what may show up in future. If I leave this with AnyObject I'm sentenced to casting everything I want to use it and if I declare it as Double there's no sense in calling this BasicModel but rather BasicDoubleModel or similar.
Do you have some hints how to achieve this? Or maybe I'm trying to solve this the wrong way?
You probably want to define a protocol with an "associated type",
this is roughly similar to generic types.
From "Associated Types" in the Swift book:
When defining a protocol, it is sometimes useful to declare one or
more associated types as part of the protocol’s definition. An
associated type gives a placeholder name (or alias) to a type that is
used as part of the protocol. The actual type to use for that
associated type is not specified until the protocol is adopted.
Associated types are specified with the typealias keyword.
In your case:
protocol BasicModel: HealthKitInitializable, ParseConvertible {
typealias ValueType
var value: ValueType { get set }
}
Then classes with different types for the value property can
conform to the protocol:
class A : BasicModel {
var value : Int
func toParseObject() -> PFObject? { ... }
required init?(sample: HKSample) { ... }
}
class B : BasicModel {
var value : Double
func toParseObject() -> PFObject? { ... }
required init?(sample: HKSample) { ... }
}
For Swift 2.2/Xcode 7.3 and later, replace typealias in the
protocol definition by associatedtype.

Swift generics and protocols issue

I'm trying to push MVVM patterns on my application, but I've found that quite difficult using Swift and Generics. Example:
I have a Comic struct on my model layer. But I want my viewControllers to consume objects conforming ComicViewModel protocol in order to increase separation of concerns.
I'm wrapping the model structs in a class called Box defined like this:
public class Box<T> {
public let value: T
public init(_ value: T) { self.value = value }
}
This is used only to wrap the actual return value in a Result enum like the one explained here
However, the Swift compiler doesn't seem to like the cast from Comic to ComicViewModel even if I'm clearly defining that
func sampleComics() -> Box<Comic> {...}
protocol ComicViewModel {...}
extension Comic : ComicViewModel {...}
func fetchComicsViewModel() -> Box<ComicViewModel> {
return sampleComics() //ERROR
}
Full playground available here.
Thanks a lot for your help!
Sad to say, Swift doesn't perform implicit casting like that. As of now, you have to re-Box() the value.
func fetchComicsViewModel() -> Box<ComicViewModel> {
return Box(sampleComics().value)
}