Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

swift - Check if class conforms to protocol

I am trying to make a simple Dependency Injection system for our app in swift, for 2 day now. I'm flexible to whatever solution but I would like something so I can say "give me a instance of something that conforms to this protocol" and the actual type returned can be whatever as long as it conforms to the said protocol. I have tried a great many thing including generics but managed to figure out that that can not(?) really work so now I'm down to the bare basics, something like this:

protocol AProtocol {

}

class AClass: AProtocol {

} 

class MyDiThing {
    public static func objectConformingTo(aProtocol: Any) -> Any? {
        // And here I want to do something like
        if AClass is aProtocol {
            return AClass()
        }
        return nil
    }
}

// The calling code ..
let aObject = MyDIThing.objectConformingTo(AProtocol)

It's not beautiful, I know, but right now i'm not that picky about performance/bad code as long as it solves the decoupling problem (and preferably can be contained in the MyDIThing class). If this is impossible in swift I'm open to other solutions. I have used similar solutions with objective-c with good success, just having a dictionary with keys being NSStringFromProtocol and values being the class, subscripting the dictionary with the inbound protocol and instantiating the class. Super simple. In swift it feels impossible!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The comment given by nhgrif is the correct answer for Swift 2. You should use an optional binding:

if let aObjectWithAProtocol = aObject as? AProtocol {
    // object conforms to protocol
    someObject.someFunction(aObjectWithAProtocol)
} else {
    // object does not conform to protocol
}

This if let something = obj as? type statement is called optional binding and checks if the object can be type-casted to the given type/class/protocol/....

If so, you can use the optional (as?) or force unwrap (as!) the object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...