向Swift中的所有对象添加扩展/方法 [英] Add an extension/method to all objects in Swift

查看:178
本文介绍了向Swift中的所有对象添加扩展/方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,所有对象都可以视为id类型,几乎所有对象都继承自NSObject. (块没有,但这是唯一的例外.)

In Objective-C, all objects can be treated as type id, and nearly all objects inherit from NSObject. (Blocks don't, but that's about the only exception.)

因此可以创建一个扩展所有Objective-C对象的Objective-C类别. (忽略块)

Thus it's possible to create an Objective-C category that extends ALL Objective-C objects. (ignoring blocks)

在Objective-C中,我创建了NSObject的扩展,该扩展使用关联的对象将字典附加到任何NSObject.这使我能够实现方法setAssocValue:forKey:assocValueForKey:,从而可以将键/值对附加到任何NSObject.在许多情况下这很有用.

In Objective-C, I created an extension to NSObject that uses associated objects to optionally attach a dictionary to any NSObject. That enabled me to implement methods setAssocValue:forKey: and assocValueForKey: that makes it possible to attach a key/value pair to any NSObject. This is useful in lots of circumstances.

例如,可以将存储的属性添加到类别.您只需编写一个使用关联的value方法连接存储对象的getter/setter即可.

It makes it possible to add stored properties to a category, just for example. You just write a getter/setter that uses the associated value methods to attach a stored object, and away you go.

还可以在运行时将值附加到现有系统对象.您可以将数据或代码块挂在按钮上,或者做任何您需要做的事情.

It also makes it possible to attach values to existing system objects at runtime. You can hang data or blocks of code on buttons, or do whatever you need to do.

我想在Swift中做同样的事情.

I'd like to do the same thing in Swift.

但是,Swift没有像Objective-C一样为所有对象提供通用的基类. AnyObjectAny是协议.

However, Swift does not have a common base class for all objects like Objective-C does. AnyObject and Any are protcols.

因此

extension AnyObject

不会编译.

我不知道在哪里将我的setAssocValue:forKey:assocValueForKey:方法附加"到哪里.

I'm at a loss as to where to "attach" my setAssocValue:forKey: and assocValueForKey: methods in Swift.

我可以为扩展名创建一个基类,但是这违背了使用扩展名的观点.我可以将我的基础对象设置为Objective-C NSObject,但这意味着我的所有对象都必须是NSObject,默认情况下Swift对象不是NSObject.

I could create a base class for my extension, but that defeats the point of using an extension. I could make my base object an Objective-C NSObject, but that means all my objects have to be NSObjects, and Swift objects are not NSObjects by default.

(顺便说一句,这个问题适用于Mac OS和iOS平台)

(BTW, this question applies to both the Mac OS and iOS platforms)

推荐答案

否.您几乎已经回答了自己的问题-Swift对象没有基类,而解决该问题的唯一真正方法是从NSObject继承.

No. You've pretty much answered your own question--Swift objects don't have a base class, and the only real way to get around it is to inherit from NSObject.

这篇关于向Swift中的所有对象添加扩展/方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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