检查Swift中是否存在功能 [英] Check if a func exists in Swift

查看:88
本文介绍了检查Swift中是否存在功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在调用函子之前检查它是否存在.例如:

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))
    }

我想调用touchMoved(Int,Int)(如果存在).有可能吗?

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

推荐答案

您可以使用可选的链接运算符:

You can use the optional chaining operator:

这似乎仅适用于已定义@Optional函数的ObjC协议.似乎还需要强制转换为AnyObject:

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

奇怪的是,在上面的示例中,甚至没有为"SomeRandomClass"声明协议"SomeRandomProtocol" ...但是,如果没有协议定义,链接运算符会给出一个错误-至少在操场上.似乎编译器需要先前声明的函数原型才能使?()运算符起作用.

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.

有关可选链算符及其在这种情况下的工作方式的更多信息,请参见深入的swift互操作性"会话.

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

这篇关于检查Swift中是否存在功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆