Swift restricts the generic type to Type.

How can I restrict a type of a generic type to a type, rather than an instance of the type?

If I have a class:

class SomeClass<T: SomeProtocol> {}

how can I guarantee that it Tis only an instance AnyClass(which is simple AnyObject.Type)

My protocol has only static methods and to call these methods I need to do instance.dynamicType.protocolMethodwhile I want to dosomeType.protocolMethod

+4
source share
2 answers

AFAIK, Swift does not allow using the metatype as a generic type. (I think this is similar to what Sam Giddins wished for in Swift 3. )

. , T , :

protocol SomeProtocol {
    static func foo()
}

struct Concrete: SomeProtocol {
    static func foo() {
        print("I am concrete")
    }
}

class SomeClass {
    let T: SomeProtocol.Type

    init(T: SomeProtocol.Type) {
        self.T = T
    }

    func go() {
        T.foo()  // no need for dynamicType
    }
}

SomeClass(T: Concrete.self).go()

, , , . , , :

class SomeClass<U: SomeProtocol> {
    let T: U.Type

    init(T: U.Type) {
        self.T = T
    }

    func go(value: U) {
        T.foo()
    }
}

SomeClass(T: Concrete.self).go(Concrete())
+1
protocol P {
    static func foo()
}
class A : P {
    static func foo() {
        print("A class")
    }
}
class B : P {
    static func foo() {
        print("C class")
    }
}

var type1 = A.self
var type2 = B.self

func check(cls: AnyClass)->Void {
    switch cls {
    case is A.Type:
        A.foo()
    case is B.Type:
        B.foo()
    default:
        break
    }
}

check(type1) // A class
check(type2) // C class

let i = Int.self         // Int.Type
let ao = AnyObject.self  // AnyObject.Protocol
let ac = AnyClass.self   // AnyClass.Protocol
let p = P.self           // P.Protocol
let f = check.self       // (AnyClass)->Void

protocol P {
    static func f()
}
class A : P {
    static func f() {
        print("A")
    }
}
class B : P {
    static func f() {
        print("B")
    }
}

func f(cls: P.Type) {
    cls.f()
}

f(A)  // A
f(B)  // B

class Test<T: P> {
    func foo() {
        T.f()
    }
}

Test<A>().foo() // A
Test<B>().foo() // B
0

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


All Articles