Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - How to get class that extended from protocol?

Is there a way that I could get the Class type or Struct type that extended my Protocol?

Here are my sample code:

protocol a {}

extension a {
    static func list(completion: ([StructType] -> Void)) {
        var items = [StructType]()
        ...
        completion(items)
    }
}

struct b{}
extension b: a {}

struct c{}
extension c: a{}

In this case I want to dynamically get the type of struct a and b, so that I could generate a list of it and return.

Thank you in advance for kindly answering my question.

like image 487
Norak Avatar asked Mar 06 '17 09:03

Norak


1 Answers

Use the Self keyword

protocol P {
    init()
}

extension P {
    static func list(completion: ([Self]) -> Void) {
        let items = [Self(), Self(), Self()]
        print(Self.self)
        completion(items)
    }
}

struct B {}
extension B: P {}

class C {
    required init() {}
}
extension C: P {}

B.list{ print($0) }
C.list{ print($0) }
like image 167
Alexander Avatar answered Nov 14 '22 00:11

Alexander