Swift 相当于@encode [英] Swift equivalent of @encode

查看:102
本文介绍了Swift 相当于@encode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有与 Objective-C 的 @encode 等效的 Swift?

例如

@encode(void *)//->@"^v"

搜索一无所获.

解决方案

不,没有 - 因为在幕后 Swift 类不使用 Objective-C 自省来完成他们的工作.没有必要计算这个(就像在 Objective-C 中那样)来传递/调用数据.

但是,如果您需要在运行时动态使用它(例如,为了与现有的 Objective-C 方法进行互操作),那么您可以创建一个 Objective-C 调用并传递对象,或者(对于简单类型)编写查找表.

类型编码列于 https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html 有地图,并且可以编写一个开关类型语句来进行查找.>

但从根本上说,如果你有一个类型想要传入并且发现它是客观的c编码类型,你可以使用NSObject的objCType方法:

var i = 1 作为 NSNumberString.fromCString(i.objCType)!==q"

如果您无论如何都需要将其作为未受干扰的 C 字符串传递,您甚至可能不需要将其转换回 Swift 字符串类型.

Is there a Swift equivalent to Objective-C's @encode?

For instance

@encode(void *) // -> @"^v"

Searching yielded nothing.

解决方案

No, there isn't - because under the hood Swift classes don't use Objective-C introspection to do their work. There's no need to calculate this (like there is in Objective-C) in order to pass/call data.

However, if you need to use it dynamically at runtime (say, for interoperation with existing Objective-C methods) then you can either create an Objective-C call and pass the object through or (for simple types) write a lookup table.

The type encodings are listed at https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html which have the map, and it's possible to write a switch type statement that does the lookup.

But fundamentally if you have a type that you want to pass in and find it's objective c encoding type, you can use the NSObject's objCType method:

var i = 1 as NSNumber
String.fromCString(i.objCType)! == "q" 

If you need to pass it through as an unmolested C string anyway, you may not even need to convert it back to a Swift string type.

这篇关于Swift 相当于@encode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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