快速关闭作为字典中的值 [英] Swift closure as values in Dictionary

查看:57
本文介绍了快速关闭作为字典中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Objective-C库,该库期望 NSDictionary 作为其返回类型。在 NSDictionary 内,我可以返回任何类型的值,包括块。

I'm trying to use an Objective-C library which expects a NSDictionary as its return type. Within the NSDictionary, I can return values of any type, including blocks.

我不知道是否存在一种写类似的swift方法的方法,该方法返回带有闭包或字符串作为可能值类型的Dictionary。

I cannot figure out if there is a way to write an analogous swift method that returns a Dictionary with a closure or a string as a possible value type.

我不能使用 AnyObject 作为字典的值类型,因此无法正常工作:

I can't use AnyObject as the value type for the dictionary so this doesn't work:

Dictionary<String,AnyObject> = ["Key":{(value:AnyObject) -> String in return value.description]

我得到一个不符合协议的内容来自编译器的关于和 AnyObject 的错误。

是否存在更高的级别我可以用作字典中的值类型的闭包和基本类型都遵循的类型或协议?

Is there a higher level type or protocol that both closures and basic types adhere to that I can use as the value type in a Dictionary?

推荐答案

您的基本问题在于,在Objective-C中,闭包(也称为块)被表示为NSObject(或更准确地说是透明地转换为NSObject),而在Swift中则没有这种映射。这意味着闭包不能直接存储在字典中(缺少使用Objective-C胶水)

Your basic problem is that in Objective-C closures (aka blocks) are represented as NSObject (or more precisely are transparently converted to NSObjects) while in Swift there is no such mapping. This means that closures can not be directly stored in a Dictionary (short of using objective-c glue)

我能想到的最接近的东西是包装纸枚举中的值:

The closest I can come up with is something along the lines of wrapping the value in an enum:

enum DataType {
    case AsString(String)
    case AsClosure((AnyObject)->String)
}

var dict:Dictionary<String,DataType> = [
    "string":DataType.AsString("value"),
    "closure":DataType.AsClosure({(argument:AnyObject) -> String in
        return "value"
        }
    )
]

哪个可能是更好的解决方案无论如何,因为这样一来,您就拥有了与各个参数相关联的显式类型,而不是使用某种形式的弯曲来隐式地进行。

Which is probably a better solution anyway, because this way you have an explicit typing associated with individual arguments instead of it being implicit using some sort of inflection.

或者,您只能包装闭包并使用类型为 Dictionary< String,Any> 的字典。

Alternatively, you could only wrap the closure and use a dictionary of type Dictionary<String,Any>.

这篇关于快速关闭作为字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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