Check if a func exists in Swift

霸气de小男生 提交于 2019-12-10 09:19:21

问题


I wish to check if a func exists before I call it. For example:

    if let touch: AnyObject = touches.anyObject() {
        let location = touch.locationInView(self)
        touchMoved(Int(location.x), Int(location.y))
    }

I would like to call touchMoved(Int, Int) if it exists. Is it possible?


回答1:


You can use the optional chaining operator:

This seems to only work with ObjC protocols that have @optional functions defined. Also seems to require a cast to AnyObject:

import Cocoa

@objc protocol SomeRandomProtocol {
    @optional func aRandomFunction() -> String
    @optional func anotherRandomFunction() -> String
}

class SomeRandomClass : NSObject {
    func aRandomFunction() -> String {
        return "aRandomFunc"
    }
}

var instance = SomeRandomClass()
(instance as AnyObject).aRandomFunction?()       //Returns "aRandomFunc"
(instance as AnyObject).anotherRandomFunction?() //Returns nil, as it is not implemented

Whats weird is that in the example above, the protocol "SomeRandomProtocol" is not even declared for "SomeRandomClass"... yet without the protocol definition, the chaining operator gives an error-- in the playground at least. Seems like the compiler needs a prototype of the function declared previously for the ?() operator to work.

Seems like maybe there's some bugs or work to do there.

See the "swift interoperability in depth" session for more info on the optional chaining operator and how it works in this case.



来源:https://stackoverflow.com/questions/24174422/check-if-a-func-exists-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!