Fast generalized existences

Excessive introduction aside, I want to have something like this:

let collection : Any<Sequence where .Iterator.Element == String> = ...

or

let collection : Sequence<where .Iterator.Element == String> = ...

This is called "Generic Existences" in the Apple Generics Manifesto . (I think), I really need this for a few use cases, and this:

the "P" protocol can only be used as a general restriction because it has its own or related type requirements.

makes the "first protocol-oriented language" cumbersome for me. The absence of this forces me to struggle with a system like Swift and create unfavorable general "abstract" classes where the protocol should be with associatedtype.

Here is one example that struck me the most, delegating for a generic class:

protocol GenericClassDelegate : class {
    associatedtype ItemType
    func didDoThat(who : GenericClass<ItemType>) 
}

class GenericClass<T> {
    weak var delegate : GenericClassDelegate<where .ItemType == T>? // can't do that

    func notify() {
        delegate?.didDoThat(who: self)
    }
}

GenericClassDelegate, ( Swift 3) ( , ).

Swift , :

  • - Swift, ? , ?
  • Swift ( , ), , . , ?

P.S. thunks , , , .

, :

protocol GenericClassDelegate : class {
    associatedtype ItemType
    func didDoThat(who : GenericClass<ItemType, Self>)
}

class GenericClass<T, Delegate : GenericClassDelegate> where Delegate.ItemType == T {
    weak var delegate : Delegate?

    func notify() {
        delegate?.didDoThat(who: self)
    }

    init(_ delegate : Delegate?) {
        self.delegate = delegate
    }
}

// Delegates must be final classes, otherwise it does not compile
// because I used Self in GenericClassDelegate
final class GenericClassDelegateImp<T> : GenericClassDelegate {
    typealias ItemType = T
    func didDoThat(who: GenericClass<T, GenericClassDelegateImp>) {
        print(who)
    }
}

// Usage:
var delegate = GenericClassDelegateImp<Int>()
var genericClass = GenericClass<Int, GenericClassDelegateImp<Int>>(delegate)
+4
1

- , Swift, ? , ?

, . ABI, , , Lattner "Swift 4 Phase 1".

, 2. , , Swift 4.

Swift ( , ), , . , ?

, , . , .

protocol Fancy {
    associatedtype Value
    var value: Value
}

struct FancyMatter<Value> {
    let value: Value
}

class AnyFancyBoxBase<P: FancyProtocol>: AnyFancyBox<P.Value> {
    let base: P
    override var value: P.Value { return base.value }
    init(_ base: P) { self.base = base }
}

class AnyFancyBox<Value> {
    var value: Value { fatalError() }
}

var box: AnyFancyBox<Int> = AnyFancyBoxBase(FancyMatter(1))

, .

+2

Source: https://habr.com/ru/post/1654453/


All Articles